node.js 没有 'Access-Control-Allow-Origin' - 节点/Apache 端口问题
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18310394/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
No 'Access-Control-Allow-Origin' - Node / Apache Port Issue
提问by user1336103
i've created a small API using Node/Express and trying to pull data using Angularjs but as my html page is running under apache on localhost:8888 and node API is listen on port 3000, i am getting the No 'Access-Control-Allow-Origin'. I tried using node-http-proxyand Vhosts Apache but not having much succes, please see full error and code below.
我已经使用 Node/Express 创建了一个小型 API 并尝试使用 Angularjs 提取数据,但是由于我的 html 页面在 localhost:8888 上的 apache 下运行并且节点 API 在端口 3000 上侦听,我得到了 No 'Access-Control-允许起源'。我尝试使用 node-http-proxy和 Vhosts Apache 但没有太多成功,请参阅下面的完整错误和代码。
XMLHttpRequest cannot load localhost:3000. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'localhost:8888' is therefore not allowed access."
XMLHttpRequest 无法加载 localhost:3000。请求的资源上不存在“Access-Control-Allow-Origin”标头。因此,不允许访问 Origin 'localhost:8888'。”
// 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').then(function(response) {
var data = response.data;
$scope.contractors = data;
})
HTML
HTML
<body ng-app="contractorsApp">
<div ng-controller="ContractorsCtrl">
<ul>
<li ng-repeat="person in contractors">{{person.name}}</li>
</ul>
</div>
</body>
回答by jvandemo
Try adding the following middleware to your NodeJS/Express app (I have added some comments for your convenience):
尝试将以下中间件添加到您的 NodeJS/Express 应用程序中(为了您的方便,我添加了一些注释):
// 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();
});
Hope that helps!
希望有帮助!
回答by Fabiano Soriani
Accepted answer is fine, in case you prefer something shorter, you may use a plugin called corsavailable for Express.js
接受的答案很好,如果你更喜欢更短的东西,你可以使用一个名为cors的插件,可用于 Express.js
It's simple to use, for this particular case:
对于这种特殊情况,使用起来很简单:
var cors = require('cors');
// use it before all route definitions
app.use(cors({origin: 'http://localhost:8888'}));
回答by Asaf Hananel
Another way, is simply add the headers to your route:
另一种方法,只需将标头添加到您的路线中:
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:)');
});
回答by Dan Abramov
The top answerworked fine for me, except that I needed to whitelist more than one domain.
该顶端回答工作对我很好,但我需要白名单不止一个域。
Also, top answer suffers from the fact that OPTIONSrequest isn't handled by middleware and you don't get it automatically.
此外,最佳答案的问题是OPTIONS请求不是由中间件处理的,并且您不会自动获得它。
I store whitelisted domains as allowed_originsin Express configuration and put the correct domain according to originheader since Access-Control-Allow-Origindoesn't allow specifying more than one domain.
我allowed_origins在 Express 配置中存储列入白名单的域,并根据origin标头放置正确的域,因为Access-Control-Allow-Origin不允许指定多个域。
Here's what I ended up with:
这是我的结果:
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);
});
回答by Vicheanak
The answer code allow only to localhost:8888. This code can't be deployed to the production, or different server and port name.
答案代码只允许 localhost:8888。此代码无法部署到生产中,或不同的服务器和端口名称。
To get it working for all sources, use this instead:
要使其适用于所有来源,请改用:
// 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();
});
回答by monikaja
Install cors dependency in your project:
在您的项目中安装 cors 依赖项:
npm i --save cors
Add to your server configuration file the following:
将以下内容添加到您的服务器配置文件中:
var cors = require('cors');
app.use(cors());
It works for me with 2.8.4 cors version.
它适用于 2.8.4 cors 版本。
回答by dmx
This worked for me.
这对我有用。
app.get('/', function (req, res) {
res.header("Access-Control-Allow-Origin", "*");
res.send('hello world')
})
You can change * to fit your needs. Hope this can help.
您可以更改 * 以满足您的需要。希望这能有所帮助。
回答by Karthik
Hi this happens when the front end and backend is running on different ports. The browser blocks the responses from the backend due to the absence on CORS headers. The solution is to make add the CORS headers in the backend request. The easiest way is to use cors npm package.
嗨,当前端和后端在不同的端口上运行时会发生这种情况。由于缺少 CORS 标头,浏览器会阻止来自后端的响应。解决方案是在后端请求中添加 CORS 标头。最简单的方法是使用 cors npm 包。
var express = require('express')
var cors = require('cors')
var app = express()
app.use(cors())
This will enable CORS headers in all your request. For more information you can refer to cors documentation
这将在您的所有请求中启用 CORS 标头。有关更多信息,您可以参考 cors 文档
回答by Wiki
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();
}
});
回答by Ezhil Arasan
Add following code in app.js of NODEJ Restful api to avoid "Access-Control-Allow-Origin" error in angular 6 or any other framework
在 NODEJ Restful api 的 app.js 中添加以下代码以避免 angular 6 或任何其他框架中的“Access-Control-Allow-Origin”错误
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
}));

