我有一个AngularJS和NodeJS(API)应用程序。 我已经使用 CORS() nodejs 库在我的 NodeJS 上启用了 CORS。
我也包含了启用 CORS 所需的标头。
只有当我从公司计算机访问网站时,我才遇到 CORS 问题。它在我的个人电脑上工作正常。谁能指导我做错了什么。请提供任何帮助或建议。
Chrome 控制台日志:
--------------------头---------------------
常规:
Request URL:www.example.com:81/api/getdata
Request Method:GET
Status Code:503 Service Unavailable
Remote Address:111.111.11.111:81
响应标头:
Cache-Control:no-store, no-cache, must-revalidate, post-check=0, pre-check=0
Connection:close
Content-Length:973
Content-Type:text/html; charset=UTF-8
Expires:Thu, 01 Jan 1970 00:00:00 GMT
P3P:CP="CAO PSA OUR"
Pragma:no-cache
请求标头:
Accept:application/json, text/plain, */*
Accept-Encoding:gzip, deflate, sdch
Accept-Language:en-US,en;q=0.8
Connection:keep-alive
Host:www.example.com:81
Origin:http://www.example.com
Referer:http://www.example.com/
User-Agent:Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36
--------------------响应:--------------------
<html>
<head>
<title>Web Page Blocked</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<META HTTP-EQUIV="PRAGMA" CONTENT="NO-CACHE">
<meta name="viewport" content="initial-scale=1.0">
</head>
<body bgcolor="#e7e8e9">
<div id="content">
<h1>Web Page Blocked</h1>
<p>Access to the web page you were trying to visit has been blocked in accordance with company policy. Please contact your
system administrator if you believe this is in error.</p>
<p><b>User:</b> </p>
<p><b>URL:</b> www.example.com:81/api/getdata </p>
<p><b>Category:</b> unknown </p>
</div>
</body>
</html>
浏览器控制台错误:
XMLHttpRequest 无法加载 http://www.example.com:81/api/getdata。不 "访问控制允许源"标头存在于请求的上 资源。因此不允许使用原产地"http://www.example.com" 访问。响应具有 HTTP 状态代码 503。
------编辑----- 这是我正在通过的cors()。
app.options('*',cors());
app.use(function (req, res, next){
res.header("Access-Control-Allow-Origin", "*");
res.setHeader("Access-Control-Allow-Methods", "GET, POST, OPTIONS, PUT, PATCH, DELETE");
res.header("Access-Control-Allow-Methods", "GET, POST, OPTIONS, PUT, PATCH, DELETE");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With,Content-type, Accept");
res.header("Access-Control-Allow-Credentials", true);
next();
});
这要么是公司防火墙的问题,要么是 CORS 问题。 尝试接受 CORS 模块中的每个源:
var express = require('express');
var cors = require('cors')
var app = express();
var corsOptions = {
origin: '*',
optionsSuccessStatus: 200 // some legacy browsers (IE11, various SmartTVs) choke on 204
};
app.get('/products/:id', cors(corsOptions), function(req, res, next){
res.json({msg: 'This is CORS-enabled for every origin.'});
});
app.listen(80, function(){
console.log('CORS-enabled web server listening on port 80');
});
现在你应该收到这样的响应标头:
HTTP/1.1 200 OK
Access-Control-Allow-Origin: *
Keep-Alive: timeout=2, max=100
Connection: Keep-Alive
Transfer-Encoding: chunked
Content-Type: application/json
如果仍然不起作用,则必须阻止端口 81。
另一种可能性是贵公司的代理删除或阻止了一些标头,这可以解释为什么响应标头中不存在Access-Control-Allow-Origin: www.example.com