POST request using fetch not working

大城市里の小女人 提交于 2019-12-23 06:12:40

问题


I'm trying to do a post call from my react application using below code.

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

However, it gives me below given error:

The same request is working in postman (API testing application). This is an application/json type request and expects same type of response.

Edit 1:

This is how the request looks on POSTMAN:

In same application GET request(below code) is working fine:

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

Relevant server side code:

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

回答1:


In case you are using http module to create server, try :

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

    // ...
});


来源:https://stackoverflow.com/questions/51872356/post-request-using-fetch-not-working

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!