我正在使用运行的NodeJS应用,
http://localhost:3000
我还有一个http://localhost:3002
上运行的NodeJS API。
我在应用程序中调用API时收到以下错误。
Failed to load http://localhost:3002: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access.
我已在server.js
的{{1}}文件中添加了CORS
http://localhost:3002
我仍然收到错误消息。每当我打开URL http://localhost:3000时,我都会在chrome开发者控制台中看到错误。
答案 0 :(得分:2)
您应该像这样使用cors
app.use(cors());
参考
Simple Usage (Enable All CORS Requests)
var express = require('express')
var cors = require('cors')
var app = express()
app.use(cors())
app.get('/products/:id', function (req, res, next) {
res.json({msg: 'This is CORS-enabled for all origins!'})
})
app.listen(80, function () {
console.log('CORS-enabled web server listening on port 80')
})
答案 1 :(得分:0)
首先尝试
npm install cors
app.use(cors())
如果它不起作用,那么 试试这个
allowCrossDomain = function(req, res, next) {
res.header('Access-Control-Allow-Credentials', true);
res.header('Access-Control-Allow-Origin', req.headers.origin);
res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');
res.header('Access-Control-Allow-Headers', 'X-Requested-With, X-HTTP-Method-Override, Content-Type, Accept');
if ('OPTIONS' === req.method) {
res.sendStatus(200);
} else {
next();
}
};
app.use(allowCrossDomain);