【问题标题】:No 'Access-Control-Allow-Origin' header is present on the requested resource in NodeJSNodeJS 中请求的资源上不存在“Access-Control-Allow-Origin”标头
【发布时间】: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:3002server.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


    【解决方案1】:

    你应该像这样使用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')
    })
    

    【讨论】:

      【解决方案2】:

      先试试吧

      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);
      

      【讨论】:

        猜你喜欢
        • 2019-04-10
        • 1970-01-01
        • 1970-01-01
        • 2013-11-29
        • 2014-07-28
        • 2014-01-19
        相关资源
        最近更新 更多