【发布时间】:2018-11-07 20:44:22
【问题描述】:
我正在使用运行在其上的 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.
我在http://localhost:3002的server.js文件中添加了CORS
var cors = require('cors');
app.options('*', cors());
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested- With, Content-Type, Accept");
next();
});
// define a simple route
app.get('/', (req, res) => {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
res.json({"message": "Welcome to Application"});
});
app.listen(3002, () => {
console.log("Server is listening on port 3002");
});
我仍然收到错误消息。每当我打开 URL http://localhost:3000 时,我都会在 chrome 开发者控制台中看到错误。
【问题讨论】:
标签: javascript node.js cors