关于node.js:否’Access-Control-Allow-Origin’ – 节点/ Apache端口问题

No 'Access-Control-Allow-Origin' - Node / Apache Port Issue

我使用Node / Express创建了一个小API并尝试使用Angularjs来提取数据,但是当我的html页面在localhost:8888上运行apache并且节点API在端口3000上侦听时,我得到了No'Access-Control-允许来源。 我尝试使用node-http-proxy和Vhosts Apache但没有取得多大成功,请参阅下面的完整错误和代码。

"XMLHttpRequest无法加载localhost:3000。请求的资源上没有'Access-Control-Allow-Origin'标头。因此不允许来自"localhost:8888"。"

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
// Api Using Node/Express    
var express = require('express');
var app = express();
var contractors = [
    {  
    "id":"1",
       "name":"Joe Blogg",
       "Weeks": 3,
       "Photo":"1.png"
    }
];

app.use(express.bodyParser());

app.get('/', function(req, res) {
  res.json(contractors);
});
app.listen(process.env.PORT || 3000);
console.log('Server is running on Port 3000')


    // Angular code
    angular.module('contractorsApp', [])
    .controller('ContractorsCtrl', function($scope, $http,$routeParams) {

   $http.get('localhost:3000').success(function(data) {

    $scope.contractors = data;

   })

   // HTML
   <body ng-app="contractorsApp">
     
       
<ul>

         <li ng-repeat="person in contractors">{{person.name}}
</li>

       
</ul>

   
   </body>

尝试将以下中间件添加到您的NodeJS / Express应用程序中(为方便起见,我添加了一些注释):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
// Add headers
app.use(function (req, res, next) {

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

    // 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的插件,可用于Express.js

对于这种特殊情况,它使用起来很简单:

1
2
3
4
var cors = require('cors');

// use it before all route definitions
app.use(cors({origin: 'http://localhost:8888'}));


另一种方法是简单地将标题添加到您的路线:

1
2
3
4
5
6
7
8
router.get('/', function(req, res) {
    res.setHeader('Access-Control-Allow-Origin', '*');
    res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE'); // If needed
    res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type'); // If needed
    res.setHeader('Access-Control-Allow-Credentials', true); // If needed

    res.send('cors problem fixed:)');
});


最佳答案对我来说很好,除了我需要将多个域列入白名单。

此外,最佳答案是因为OPTIONS请求不是由中间件处理而您没有自动获取。

我将列入白名单的域作为allowed_origins存储在Express配置中,并根据origin标头放置正确的域,因为Access-Control-Allow-Origin不允许指定多个域。

这是我最终得到的:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
var _ = require('underscore');

function allowCrossDomain(req, res, next) {
  res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS');

  var origin = req.headers.origin;
  if (_.contains(app.get('allowed_origins'), origin)) {
    res.setHeader('Access-Control-Allow-Origin', origin);
  }

  if (req.method === 'OPTIONS') {
    res.send(200);
  } else {
    next();
  }
}

app.configure(function () {
  app.use(express.logger());
  app.use(express.bodyParser());
  app.use(allowCrossDomain);
});


答案代码仅允许localhost:8888。此代码无法部署到生产环境,或者不同的服务器和端口名称。

要使其适用于所有来源,请使用此代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
// Add headers
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依赖项:

1
npm i --save cors

将以下内容添加到服务器配置文件中:

1
2
var cors = require('cors');
app.use(cors());

它适用于我的2.8.4 cors版本。


这对我有用。

1
2
3
4
5
app.get('/', function (req, res) {

    res.header("Access-Control-Allow-Origin","*");
    res.send('hello world')
})

您可以更改*以满足您的需求。希望这可以提供帮助。


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
app.all('*', function(req, res,next) {
    /**
     * Response settings
     * @type {Object}
     */
    var responseSettings = {
       "AccessControlAllowOrigin": req.headers.origin,
       "AccessControlAllowHeaders":"Content-Type,X-CSRF-Token, X-Requested-With, Accept, Accept-Version, Content-Length, Content-MD5,  Date, X-Api-Version, X-File-Name",
       "AccessControlAllowMethods":"POST, GET, PUT, DELETE, OPTIONS",
       "AccessControlAllowCredentials": true
    };

    /**
     * Headers
     */
    res.header("Access-Control-Allow-Credentials", responseSettings.AccessControlAllowCredentials);
    res.header("Access-Control-Allow-Origin",  responseSettings.AccessControlAllowOrigin);
    res.header("Access-Control-Allow-Headers", (req.headers['access-control-request-headers']) ? req.headers['access-control-request-headers'] :"x-requested-with");
    res.header("Access-Control-Allow-Methods", (req.headers['access-control-request-method']) ? req.headers['access-control-request-method'] : responseSettings.AccessControlAllowMethods);

    if ('OPTIONS' == req.method) {
        res.send(200);
    }
    else {
        next();
    }


});


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
//Add following code in app.js of NODEJ Restful api to avoid"Access-Control-Allow-Origin" error in angular 6 or any other framework

var express = require('express');
var app = express();

var cors = require('cors');
var bodyParser = require('body-parser');

//enables cors
app.use(cors({
  'allowedHeaders': ['sessionId', 'Content-Type'],
  'exposedHeaders': ['sessionId'],
  'origin': '*',
  'methods': 'GET,HEAD,PUT,PATCH,POST,DELETE',
  'preflightContinue': false
}));


你可以使用"$ http.jsonp"

要么

以下是针对本地测试的chrome的解决方法

您需要使用以下命令打开chrome。 (按窗口+ R)

1
Chrome.exe --allow-file-access-from-files

注意:您的chrome不能打开。运行此命令时,chrome将自动打开。

如果要在命令提示符下输入此命令,请选择chrome安装目录,然后使用此命令。

下面是MAC中打开chrome的脚本代码,带有"--allow-file-access-from-files"

1
2
3
set chromePath to POSIX path of"/Applications/Google Chrome.app/Contents/MacOS/Google Chrome"
set switch to" --allow-file-access-from-files"
do shell script (quoted form of chromePath) & switch &"> /dev/null 2>&1 &"

第二种选择

你可以使用open(1)来添加标志:open -a'Google Chrome'-args --allow-file-access-from-files


嗨,当前端和后端在不同的端口上运行时会发生这种情况。由于缺少CORS标头,浏览器会阻止来自后端的响应。解决方案是在后端请求中添加CORS头。最简单的方法是使用cors npm包。

1
2
3
4
var express = require('express')
var cors = require('cors')
var app = express()
app.use(cors())

这将在您的所有请求中启用CORS标头。有关更多信息,请参阅cors文档

https://www.npmjs.com/package/cors


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
/**
 * Allow cross origin to access our /public directory from any site.
 * Make sure this header option is defined before defining of static path to /public directory
 */
expressApp.use('/public',function(req, res, next) {
    res.setHeader("Access-Control-Allow-Origin","*");
    // Request headers you wish to allow
    res.setHeader("Access-Control-Allow-Headers","Origin, X-Requested-With, Content-Type, Accept");
    // Set to true if you need the website to include cookies in the requests sent
    res.setHeader('Access-Control-Allow-Credentials', true);
    // Pass to next layer of middleware
    next();
});


/**
 * Server is about set up. Now track for css/js/images request from the
 * browser directly. Send static resources from"./public" directory.
 */
expressApp.use('/public', express.static(path.join(__dirname, 'public')));
1
If you want to set Access-Control-Allow-Origin to a specific static directory you can set the following.