node.js - 如何在nodeJS服务器上允许cors

我有一个带有 node.js 的超级简单的 backend,并且我启用了 CORS。但是,我仍然无法允许跨域发送任何类型的数据。

这是我在 3000 端口上运行的 backend :

const express = require('express');
const cors = require('cors');

const app = express();

var corsOptions = {
    origin: 'http://127.0.0.1:3001',
    optionsSuccessStatus: 200 // For legacy browser support
}

app.use(cors(corsOptions));

//app.use(cors()); ALSO TRIED THIS

app.listen('3000', () => {
    console.log('Listening on port 3000');
});


app.get('/number', (req, res) => {
    res.json({number: 1});
});

这就是我从前端 fetch 在端口 3001 上运行的方式:

fetch('http://localhost:3000/number')
    .then(res => console.log(res));

但这是我得到的回应:

Response {
    body: ReadableStream
    bodyUsed: false
    headers: Headers {}
    ok: true
    redirected: false
    status: 200
    statusText: "OK"
    type: "cors"
    url: "http://localhost:3000/number"
}

但我期待:

Response {
    number:1
}

我认为这主要是一个 CORS 问题,因为使用邮递员时一切正常。

非常感谢您的参与!

回答1

这不是 cors 问题,只需像打击一样更改您的 fetch 即可获得预期的结果。

fetch('http://localhost:3000/number')
    .then(res => res.json()).then(data=>console.log(data));

这会给你 {number: 1} 结果。

相似文章

随机推荐

最新文章