节点js允许所有域的Access-Control-Allow-Origin

时间:2017-05-05 22:29:08

标签: node.js reactjs cors

我目前正在研究节点js / react api,我有 " No' Access-Control-Allow-Origin'"错误并修复它。 我的代码目前看起来像这样:

app.use(function (req, res, next) {
    res.setHeader('Access-Control-Allow-Origin', 'http://localhost:8888');
    res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');
    res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type');
    res.setHeader('Access-Control-Allow-Credentials', true);
    next();});

现在我想授权访问每个域名,每个人都可以进行GET,POST ...请求,我怎么能这样做?

1 个答案:

答案 0 :(得分:0)

试一试:

app.use(function (req, res, next) {
    res.setHeader('Access-Control-Allow-Origin', '*');
    res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');
    res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type');
    res.setHeader('Access-Control-Allow-Credentials', true);
    next();});

我不确定这会起作用。 如果它不起作用并且您想要最简单的解决方案,请尝试此包https://www.npmjs.com/package/cors

var cors = require('cors')

var app = express()
app.use(cors())