I have to make a post request to an api endpoint, but I get an error status 500.
name: "HttpErrorResponse"
ok: false
status: 500
statusText: "Internal Server Error"
This is my code:
var selectedIds = ["31"];
let sendData = new FormData();
sendData.append('auth', this.dataService.REG_AUTH);
sendData.append('identifier', identifier);
sendData.append('selected[]', selectedIds);
this.http.post<any>('APIENDPOINT', sendData).subscribe(data => {
console.log(data);
}, error => {
console.log(error);
});
The issue is in this line: sendData.append('selected[]', selectedIds); I have no clue how to pass an array to FormData.
This is a working example from our android app. I need to convert this request in angular/typescript syntax:
#JvmSuppressWildcards
#FormUrlEncoded
#POST("APIENDPOINT")
fun addData(
#Field("auth") auth: String,
#Field("identifier") identifier: String,
#Field("selected[]") selected: ArrayList<String>
): Call<ResponseBody>
What I know so far:
It seems angular does not serialize the data, so I tried some hardcoded fixes, but none of these worked:
sendData.append('selected%5B%5D', '%2231%22');
sendData.append('selected%5B%5D', '31');
sendData.append('selected%5B%5D', 31);
sendData.append('selected%5B%5D', '%5B%2231%22%5D');
sendData.append('selected%5B%5D', selectedIds);
sendData.append('selected%5B%5D', JSON.stringify(selectedIds));
If I use selected instead of selected[], then I get no error, but obviously no data is updated, so I am pretty sure it is a serialization/parsing issue.
From this answer:
FormData's append() method can only accept objects of string or blob
type. If you need to append the array, use JSON.stringify() method to
convert your array into a valid JSON string.
formData.append('selected[]', JSON.stringify(selectedIds));
The statusCode 500 is the Internal Server Error, and it's the server-side problem. So, It's better to check the API if it can receive your request or not.
FormData's append() method accept string or blob type So you can use JSON.stringify() method (formData.append('selectedIds', JSON.stringify(selectedIds));). So try this:
let selectedIds = ["31"];
let sendData = new FormData();
sendData.append('auth', this.dataService.REG_AUTH);
sendData.append('identifier', identifier);
sendData.append('selectedIds', JSON.stringify(selectedIds));
this.http.post<any>('APIENDPOINT', sendData).subscribe(data => {
console.log(data);
}, error => {
console.log(error);
});
Related
I try to send data to my NodeJS server using HTTP protocol (vue-resource). I want to send a array of JSON object like this : [{"name":"Charlotte","surname":"Chacha","birth":"2000-04-02"},{"name":"Michael","surname":"Mic","birth":"1999-01-30"}].
My front code :
window.onload = function () {
var gamme = new Vue({
el:'#gamme',
data: {
myListe: []
},
methods: {
sendListe: function() {
this.$http.get("/NewListe?liste="+this.myListe).then(response=> {
if (response.body) {
console.log(response.body);
}
});
}
}
})
}
And my back code :
server.app.get("/NewListe", function(req, res) {
try {
let liste= req.query.liste;
console.log(liste);
} catch (e) {
console.log(e);
}
})
When I try to display the variable liste in the server side console, I obtain this : [object Object] . liste is a string type that I can't use. I would like to have an array of JSON, like in front.
I tried to parse like this JSON.parse(operationsGamme) , but I have this error : SyntaxError: Unexpected token o in JSON at position 1
You should surely be using a POST method if you are sending JSON data to the server - a GET just isn't designed for that sort of usage.
Since you have passed a JSON in the url, it will be URLEncoded. So, in the backend before you do JSON.parse(liste), you should do decodeURI(liste). decodeURI() will return the JSON string which you can parse and use it in your code. I hope this will fix your problem.
I have the following Typescript function that assumes a Chrome browser has already been launched using Puppeteer. The documentation for the Fetch functions used below can be found here.
async function modify(client: CDPSession) {
client.on('Fetch.requestPaused', async ({ requestId, request, frameId, resourceType, responseErrorReason, responseStatusCode, responseHeaders, networkId }) => {
// Correctly prints out the User-Agent header's value
console.log(request.headers["User-Agent"]);
// After this line is run, I can inspect the request.headers object and see that User-Agent was successfully edited
request.headers['User-Agent'] = 'trying to edit this header';
// Continuing the request gives an error
await client.send('Fetch.continueRequest', {
requestId: requestId,
headers: request.headers,
});
});
}
Here is the specific error I'm seeing:
Error: Protocol error (Fetch.continueRequest): Invalid parameters headers: array expected
How can I resolve this error and successfully modify the request.headers? Is this a silly Javascript/Typescript syntax issue that I just can't figure out?
Fetch.requestPaused returns the headers as an object. e.g.:
{
"Upgrade-Insecure-Requests":"1",
"Accept": "text/html,application/xhtml+xml"}
}
Fetch.continueRequest expects an Array<{name: string, value: string}>. e.g.
[
{"name": "Accept", value: "text/html,application/xhtml+xml"}
]
You can use the code that Puppeteer is using:
function headersArray(headers) {
const result = [];
for (const name in headers) {
if (!Object.is(headers[name], undefined))
result.push({name, value: headers[name] + ''});
}
return result;
}
I am trying to send an image through a resource and recovery in a php file but I have not succeeded, this is my JS file:
//* AJAX *//
startAsyncNews: function(){
if(this.sendimage){
var formdata = new FormData();
formdata.append("file",this.contentnew.imageFile );
console.log(this.contentnew.imageFile);
}
// POST /someUrl
this.$http.post('controllers/newsController.php', {
data:{action : this.accion_new, data_new: this.contentnew , imgf : formdata}
}).then(response => {
}, response => {
console.log("error");
});
},
imageSelect: function($event){
this.sendimage=true;
this.contentnew.imageFile =$event.target.files[0];
}
When I use the console.log = console.log (this.contentnew.imageFile), it shows me the properties of the image correctly, that is, it is sending the file well, but when I receive it in php and I do vardump I get this object ( stdclass) # 3 (0) no properties no properties and with json_decode / encode I get it empty, also try
headers: {
'content-type': 'multipart/form-data'
}
But it generates the following error:
Missing boundary in multipart/form-data POST
You need to add all your data in formdata Object using formdata.append(key,value) function.
Then you simply send formdata
formdata.append('action ',this.accion_new);
formdata.append('data_new',this.contentnew);
this.$http.post('controllers/newsController.php', {
data:formdata
});
// or just if i'm not mistaken
this.$http.post('controllers/newsController.php',formdata);
object in http request data.
I don't know what this.accion_new and this.contentnew are, but this line:
this.$http.post('controllers/newsController.php', {
data:{action : this.accion_new, data_new: this.contentnew , imgf : formdata}
})
should simply be be:
this.$http.post('controllers/newsController.php', formdata)
Sorry if trivial, or already asked, I can't find any question about that. I dont't know if I'doing right too...
I just beginned learning service workers:
I'd like to return some json object from a service worker for a specific request. N.B.: The code is just testing/learning code:
Service Worker Fetching Event:
self.addEventListener('fetch', function(event) {
if(event.request.url.indexOf("not_existing.json") > -1){
var obj = { "Prop" : "Some value" };
event.respondWith(
new Response(obj, {
ok: true,
status: 222,
url: '/'
})
);
}});
Fetch Call:
fetch('not_existing.json')
.then(function(responseObj) {
console.log('status: ', responseObj.status);
return responseObj.json();
})
.then(function (data){
console.log(data);
});
I know that the service worker catches the request, because on "console.log('status: ', responseObj.status);" I get "222", but the script breaks on "return responseObj.json();" with error "Uncaught (in promise) SyntaxError: Unexpected token o in JSON at position 1"
If I return "plain text" from service worker, and read it with "responseObj.text()" all works great!
On this link "https://developer.mozilla.org/en-US/docs/Web/API/Response/Response" it seems I have only to write the body on Response constructor var myResponse = new Response(body, init);
What's wrong? How to specify the json response object?
You're not actually creating a response with JSON. The first argument of Response is a string or a few others, but not a random object. If you want JSON, you need to actually pass JSON, e.g.
var obj = JSON.stringify({ "Prop" : "Some value" });
The error you are getting is because currently it is converted to a string as
"[object Object]"
and
JSON.parse("[object Object]")
throws unexpected token "o".
I'm having trouble using JavaScript to send xml. I've tried to emulate what many others have done, but I'm not getting success. I'm getting a XML Syntax Error: Please check the XML request to see if it can be parsed. with the code 80040B19.
Here's my code. I'm trying to use the USPS Address Validation API. On page 4 of this doc, there's more info.
const apiUrl = 'http://production.shippingapis.com/ShippingAPI.dll?API=Verify';
validate(address: Object): any {
const payload = this.xmlBuilder.buildObject({
AddressValidateRequest: {
$: { USERID: 'XXXXXXXXX' }, // api key hidden
Address: {
$: { ID: '0'},
FirmName: null,
Address1: address['address2'],
Address2: address['address1'], // NOT A TYPO, they swap it
City: address['city'],
State: 'NY',
Zip5: address['postal_code'],
Zip4: null
}
}
});
console.log(payload); // SEE BELOW
const headers = new Headers({ 'Content-Type': 'text/xml' });
const options = new RequestOptions({ headers: headers });
return this.http.post(this.apiUrl, { 'XML': payload }, options)
.map((res) => {
this.parseXMLStringToObject(res.text(), (err, result) => {
console.log(result);
});
});
}
Here's what my console.log on the payload reads. I've verified this to the letter, from the order of the xml tags, to what is required tag but optional value. I'm positive the payload is correct.
<AddressValidateRequest USERID="XXXXXXXXX">
<Address ID="0">
<FirmName/>
<Address1/>
<Address2>620 Eighth Avenue</Address2>
<City>New York</City>
<State>NY</State>
<Zip5>10018</Zip5>
<Zip4/>
</Address>
</AddressValidateRequest>
One thing that I can think of is I'm somehow not using the http correctly, and I'm sending a blank xml somehow.
On their docs, they have this listed:
https://servername/ShippingAPI.dll?API=Verify&XML=……..
I noticed I'm not doing a XML in the url, but I'm assuming that when I input the Content-Type: text/xml, that it get converted. I've also tried application/xml which give the same error.
From the documentation on USPS website it seems that the call isn't a POST with the XML as payload but a GET with XML (I suppose urlencoded) in the URL XML parameter.