[英]Request works in POSTMAN but not by FETCH
I am running into some trouble trying to figure out why my request is working on postman but not in the app (using fetchjs). 我在尝试弄清楚为什么我的请求在邮递员上却无法在应用程序中正常工作时遇到了一些麻烦(使用fetchjs)。 The following is my request in the postman: 以下是我在邮递员中的要求:
The Following is my code in node app using fetchjs: 以下是我在使用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). r实际上是方法(读取)的一部分。
Any idea on what i am doing wrong ? 关于我在做什么错的任何想法吗? Any Suggestion is much appreciated. 任何建议深表感谢。
In line 5: let vals = [method,vals,id];
在第5行中: let vals = [method,vals,id];
there are two 'vals'? 有两个“ val”?
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));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.