使用抓取的POST请求不起作用

时间:2018-08-16 08:03:57

标签: javascript reactjs fetch-api

我正在尝试使用以下代码从我的react应用程序中进行发布调用。

  writeToFile = (data = {}) => {
    let url = "http://localhost:8000/write";
    console.log(data);
    return fetch(url, {
      method: 'post',
      headers: {
        'Accept': 'application/json, text/plain, */*',
        'Content-Type': 'application/json'
      },
        body: JSON.stringify({"content": "some content"})
      }).then(res=>res.json())
        .then(res => console.log(res));
  }                     

但是,它给了我以下错误:

enter image description here

相同的请求正在邮递员(API测试应用程序)中工作。这是一个application/json类型的请求,需要相同类型的响应。

编辑1:

这是请求在POSTMAN上的样子:
enter image description here

在同一应用程序GET中的请求(以下代码)运行正常:

  readFromFile = () => {
    fetch('http://localhost:8000/read')
      .then(function(response) {
        return response.json();
      })
      .then((myJson) => {
        console.log(myJson.content);
        this.setState({messages: this.state.messages.concat({content: myJson.content, type: 'received'})});
        console.log(this.state.messages);
      });
  }             

相关服务器端代码:

function writeToFile(request, response) {
    var body = '';

    request.on('data', function (data) {
        body += data;
        // Too much POST data, kill the connection!
        // 1e6 === 1 * Math.pow(10, 6) === 1 * 1000000 ~~~ 1MB
        if (body.length > 1e6)
            request.connection.destroy();
    });

    request.on('end', function () {
        // const dataToWrite = JSON.parse(body)["content"];
        // console.log(dataToWrite);
        myFileModule.fileWriter(JSON.parse(body)["content"]);
        response = allowCORS(response);
        response.writeHead(200, {'Content-Type': 'application/json'});
        response.write(JSON.stringify({ content: "success..." }));
        response.end();
    });
}

function postRequestHandler(request, response) {

    var path = url.parse(request.url).pathname;

    switch (path) {
        case '/write':
            writeToFile(request, response);
            break;
        default:
            response = allowCORS(response);
            response.writeHead(404, {'Content-Type': 'application/json'});
            response.write(JSON.stringify({ content: "Path not defined" }));
            response.end();
            break;
    }
}


function allowCORS(response) {
    response.setHeader('Access-Control-Allow-Origin', '*');
    response.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE'); // If needed
    response.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type'); // If needed
    response.setHeader('Access-Control-Allow-Credentials', true); // If needed
    return response;
}

2 个答案:

答案 0 :(得分:1)

如果您使用http模块创建服务器,请尝试:

var server;
server = http.createServer(function(req,res){
    // Set CORS headers
    res.setHeader('Access-Control-Allow-Origin', '*');
    res.setHeader('Access-Control-Request-Method', '*');
    res.setHeader('Access-Control-Allow-Methods', 'OPTIONS, GET, POST, PATCH, DELETE, PUT');
    res.setHeader('Access-Control-Allow-Headers', '*');
    if ( req.method === 'OPTIONS' ) {
        res.writeHead(200);
        res.end();
        return;
    }

    // ...
});

答案 1 :(得分:-1)

您尝试使用POST(全部大写)而不是post吗?