首页 > 解决方案 > React - REST:javascript fetch 帖子空正文

问题描述

fetch(REST+'/signup', {
    mode: 'cors',
    method: 'POST',
    headers: {'Content-Type': 'application/json'},
    body: JSON.stringify({ id: id, pw: pw }) 
}).then(async (res) => {
    let json = await res.json();
    if (json.result === true) { 
        this.setState({ view: 'login' });
    } 
});

这是我客户的 POST 请求部分。我的反应应用程序使用端口 3000,而我的 REST 服务器使用的是 80

我已经像这样声明在我的 REST 服务器中使用 cors

app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.use(cors()); // enable CORS to prevent same origin policy error

这是我的 REST 服务器代码的其余部分

app.post('/signup', (req, res) => {
    console.log(req.body);
    ...
    res.send(JSON.stringify({
        result: true
    }));
});

当我使用 cURL 测试 REST 服务器时,它说

$ curl --header "Content-Type: application/json" --request POST --data '{"id": "gksrlf2ek", "pw": "hangil2da!"}' http://localhost/signup
{"result":true}

但使用我的反应应用程序,REST 服务器获取 {}。空对象。

标签: javascriptreactjsfetch

解决方案


推荐阅读