在POST请求后,Fetch返回空JSON

时间:2018-03-17 13:07:03

标签: express fetch

我正在使用Fetch API向我的Express服务器发送POST请求,但我总是得到空的JSON({}),而不是我发送的数据。

var postData = function (url, data) {
    return fetch(url, {
        body: JSON.stringify(data),
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        }
    })
    .then(function (response) {
        return response.json();
    })
    .then(function (data) {
        return data;
    });
};

var firstField = document.querySelector('#first-field').value;
var secondField = document.querySelector('#second-field').value;

if (firstField.trim().length && secondField.trim().length) {
    postData('http://localhost:3000/test', { x: firstField, y: secondField })
    .then(function (data) { console.log(data) })
    .catch(function (error) { console.error(error) });
}

这是Express路线:

app.post('/test', (req, res, next) => {
    const x = req.body.x;
    const y = req.body.y;

    res.send(JSON.stringify({
        x: x,
        y: y
    }));
});

1 个答案:

答案 0 :(得分:0)

昨天花了很多钱解决这个问题。

您可以通过安装cors中间件来解决该问题。 https://www.npmjs.com/package/cors

npm install cors

并将其添加到您的应用中。在身体分析者之前。

app.use( cors() )
app.use( bodyparser.urlencoded({ extended: true }) )

这应该修复Fetch API返回的空主体表达。显然使用jQuery ajax发布请求是开箱即用的。尚未进一步调查原因。

祝你好运。

/ S