请求在POSTMAN中有效,但在FETCH中无效

时间:2018-02-05 06:34:05

标签: node.js fetch postman

我遇到了一些麻烦,试图找出我的请求为什么在postman上工作但不在app中(使用fetchjs)。 以下是邮递员的要求: enter image description here

以下是使用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))
}

以下是我的快速服务器代码:

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];

我收到以下回复:

SyntaxError: Unexpected token r"

r实际上是方法的一部分(读取)。

对我做错了什么的任何想法?任何建议都非常感谢。

3 个答案:

答案 0 :(得分:0)

在第5行:let vals = [method,vals,id];有两个' val?'?

答案 1 :(得分:0)

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))
}

let vals = this.req.body.vals;
if (!vals) throw new Error('Vals Missing');
vals = JSON.parse(vals);
let method = vals[0];    

答案 2 :(得分:0)

在您的选项上使用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));