我已经使用Node/Express创建了一个小API,并试图使用Angularjs拉数据,但由于我的html页面在localhost:8888和节点API在端口3000上监听下运行,我得到了No 'Access-Control-Allow-Origin'。我尝试使用node-http-proxy和Vhosts Apache,但没有太多成功,请参阅下面的完整错误和代码。
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.module('contractorsApp', [])
.controller('ContractorsCtrl', function($scope, $http,$routeParams) {
$http.get('localhost:3000').then(function(response) {
var data = response.data;
$scope.contractors = data;
})
HTML
<body ng-app="contractorsApp">
<div ng-controller="ContractorsCtrl">
<ul>
<li ng-repeat="person in contractors">{{person.name}}</li>
</ul>
</div>
</body>
你可以使用"$http.jsonp"
OR
下面是周围的工作铬为本地测试
你需要使用以下命令打开你的chrome浏览器。(按窗口+ R)
Chrome.exe --allow-file-access-from-files
注意:你的chrome浏览器不能打开。当你运行这个命令时,chrome浏览器会自动打开。
如果你在命令提示符中输入这个命令,然后选择你的chrome安装目录,然后使用这个命令。
下面是在MAC中使用“——allow-file-access-from-files”打开chrome的脚本代码
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 '谷歌Chrome'——args——allow-file-access-from-files
尝试在你的NodeJS/Express应用程序中添加以下中间件(为了方便起见,我添加了一些注释):
// Add headers before the routes are defined
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();
});
(您可能需要使用127.0.0.1而不是localhost。)
上面的答案对我来说很好,只是我需要将多个域名列入白名单。
此外,top answer还会受到这样一个事实的影响,即OPTIONS请求不是由中间件处理的,您不能自动获得它。
我将白名单域存储为allowed_origins在Express配置中,并根据origin头放置正确的域,因为Access-Control-Allow-Origin不允许指定多个域。
这是我最后得出的结论:
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);
});
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();
}
});
/**
* 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')));
If you want to set Access-Control-Allow-Origin to a specific static directory you can set the following.
应答码只允许localhost:8888。此代码不能部署到生产环境中,也不能部署到不同的服务器和端口名称中。
要让它适用于所有源,请使用下面的代码:
// 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();
});
另一种方法是简单地添加头到你的路由:
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:)');
});
在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
}));
除了所有列出的答案外,我还犯了同样的错误
我可以访问前端和后端,我已经添加了cors模块app.use(cors());尽管如此,我还是在为这个错误而挣扎。
经过一些调试后,我发现了这个问题。当我上传一个大小超过1mb的媒体时,Nginx服务器抛出了错误
<html>
<head>
<title>413 Request Entity Too Large</title>
</head>
<body>
<center>
<h1>413 Request Entity Too Large</h1>
</center>
<hr>
<center>nginx/1.18.0</center>
</body>
</html>
但是在前台控制台,我发现了这个错误
Access to XMLHttpRequest at 'https://api.yourbackend.com' from origin 'https://web.yourfromntend.com' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
这让人很困惑。但是这个错误的路由原因来自nginx配置。这只是因为指令client_max_body_size的值默认设置为0。它决定了允许的HTTP请求大小是client_max_body_size。这个指令可能已经在你的nginx.conf文件(位于/etc/nginx/nginx.conf)中定义了。现在你需要在http或服务器上添加/编辑client_max_body_size指令的值。
server {
client_max_body_size 100M;
...
}
一旦你设置了你想要的值,保存你的更改并重新加载Nginx: service Nginx reload
经过这些改变,它运行得很好
参考:https://www.keycdn.com/support/413-request-entity-too-large: ~:文本= % 23日处理% 20 % 20 % 20的web服务器% 20。= % 20例% 20请求% 2 c % 20 % 5月20日,如% 20 % 20大% 20媒体% 20文件)。