使用fetch的POST请求不起作用 [英] POST request using fetch not working

查看:128
本文介绍了使用fetch的POST请求不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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:

同样的请求在postman(API测试应用程序)中有效。这是一个 application / json 类型的请求,并期望相同类型的响应。

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

编辑1:

这是请求在POSTMAN上的显示方式:

< a href =https://i.stack.imgur.com/zxbWq.png =nofollow noreferrer>

This is how the request looks on POSTMAN:

在同一个应用程序中 GET 请求(代码如下)正在运行罚款:

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

相关服务器端代码:

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


推荐答案

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

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

    // ...
});

这篇关于使用fetch的POST请求不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆