Node.js 中请求的资源上不存在 'Access-Control-Allow-Origin' header

No 'Access-Control-Allow-Origin' header is present on the requested resource in Node.js

我正在尝试使用基本身份验证使用 Node.js 和 express 登录我的 grafana 页面,但它显示如下错误。

'localhost:4000' 持有我的 app.js 并且 'localhost:5000' 来自 nginx proxy_pass 到我的 grafana 页面(localhost:8080)

这是我的基本授权码

app.get('/grafana', isLoggedIn, function(req, res, next){
  console.log('Accessing to grafana');
  var auth = "Basic " + new Buffer('admin' + ":" + 'admin').toString("base64");
  request({
    url: 'http://localhost:5000',
    headers:{
      "Authorization": auth
    }             //passing through here
  }, function(err, resp, body){

我的问题是什么..?我添加了 Access-Control-Allow-Origin 等,如下所示,但根本不起作用..

app.all('*', function(req, res, next) {
  res.header('Access-Control-Allow-Origin', "*");
  res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');
  res.header('Access-Control-Allow-Headers', 'Origin, Basic, X-Requested-With, Content-Type, Accept, Authorization');
  res.header('Access-Control-Allow-Credentials', 'true');
  next();
});

有人对此有想法吗...?

谢谢..

我认为,你应该安装 cors

npm install cors

简单用法:

var express = require('express');
var cors = require('cors');
var app = express();
app.use(cors());


app.use(function (req, res, next) {

        // Website you wish to allow to connect
        res.setHeader('Access-Control-Allow-Origin', '*');

        // Request methods you wish to allow
        res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');

        // Request headers you wish to allow
        res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type');

        // Set to true if you need the website to include cookies in the requests sent
        // to the API (e.g. in case you use sessions)
        res.setHeader('Access-Control-Allow-Credentials', true);

        // Pass to next layer of middleware
        next();
    });

可以参考:cors 超过 : here

这看起来类似于 question about using an Apache proxy for Grafana

此处的文档中有一个 nginx 示例:

http://docs.grafana.org/v1.9/installation/#graphite-server-config

auth_basic            "Restricted";
auth_basic_user_file  /path/to/my/htpasswd/file;

if ($http_origin ~* (https?://[^/]*\.somedomain\.com(:[0-9]+)?)) {  #Test if request is from allowed domain, you can use multiple if
    set $cors "true";                                               #statements to allow multiple domains, simply setting $cors to true in each one.
}

if ($cors = 'true') {
    add_header  Access-Control-Allow-Origin $http_origin;           #this mirrors back whatever domain the request came from as authorized, as
    add_header  "Access-Control-Allow-Credentials" "true";          #as long as it matches one of your if statements
    add_header  "Access-Control-Allow-Methods" "GET, OPTIONS";
    add_header  "Access-Control-Allow-Headers" "Authorization, origin, accept";
}

你的nginx代理是怎么配置的?