I am running into some trouble trying to figure out why my request is working on postman but not in the app (using fetchjs). The following is my request in the postman:
The Following is my code in node app using fetchjs:
fetchData() {
let body = {}
let method = "read";
let id = "ctzeN5gn5fkQqj9uc";
let vals = [method,{},id];
let headers={
"Accept": "application/json",
"Content-Type": "application/json",
};
fetch('http://localhost:8000/v1/en/reviews', {
method: 'POST',
headers:headers,
dataType:'json',
body: JSON.stringify({vals:vals})
}).then(res => res.json())
.then(res => {
console.log(res);
if (res.error) throw (res.reason);
this.setState({ data: res.data });
})
.catch(res => console.error(res))
}
The Following is my express server code:
let vals = this.req.body.vals;
if (!vals) throw new Error('Vals Missing');
let vals = JSON.parse(vals);
let method = vals[0]; //>>>error here (Unexpected token r)
let args = vals[1];
let id = vals[2];
I get the following response back :
SyntaxError: Unexpected token r"
the r is actually part of method (read).
Any idea on what i am doing wrong ? Any Suggestion is much appreciated.
In line 5: let vals = [method,vals,id];
there are two 'vals'?
fetchData() {
let body = {}
let method = "read";
let id = "ctzeN5gn5fkQqj9uc";
let vals = [method,{},id];
let headers= {'Content-Type': 'application/x-www-form-urlencoded'};
fetch('http://localhost:8000/v1/en/reviews', {
method: 'POST',
headers:headers,
body: JSON.stringify({vals:vals})
}).then(res => res.json())
.then(res => {
console.log(res);
if (res.error) throw (res.reason);
this.setState({ data: res.data });
})
.catch(res => console.error(res))
}
also
let vals = this.req.body.vals;
if (!vals) throw new Error('Vals Missing');
vals = JSON.parse(vals);
let method = vals[0];
使用mode: 'cors'
在您的选项上像mode: 'cors'
:
fetch("http://localhost:8000/v1/en/reviews", { mode: "cors", method: "POST", headers: headers, dataType: "json", body: JSON.stringify({vals: vals}) }) .then((res) => res.json()) .then((res) => { console.log(res); if (res.error) throw res.reason; this.setState({data: res.data}); }) .catch((res) => console.error(res));
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.