【发布时间】:2015-08-01 22:40:39
【问题描述】:
我可以像使用 php 一样使用 nodejs 更改超级全局变量吗?
如果没有,那么任何人都可以向我指出一个关于如何从客户端进行跨域 http 请求的简单教程吗?你知道,阻止 ajax 到另一个域的 CORS 吗?
【问题讨论】:
标签: php ajax node.js cors superglobals
我可以像使用 php 一样使用 nodejs 更改超级全局变量吗?
如果没有,那么任何人都可以向我指出一个关于如何从客户端进行跨域 http 请求的简单教程吗?你知道,阻止 ajax 到另一个域的 CORS 吗?
【问题讨论】:
标签: php ajax node.js cors superglobals
如果您使用的是 Express 之类的框架,CORS can be done like this:
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();
});
app.get('/', function(req, res, next) {
// Handle the get for this route
});
app.post('/', function(req, res, next) {
// Handle the post for this route
});
或者,更简单的是,使用 cors 中间件。
或者,您也可以使用this gist 作为起点:
if (req.method === 'OPTIONS') {
console.log('!OPTIONS');
var headers = {};
// IE8 does not allow domains to be specified, just the *
// headers["Access-Control-Allow-Origin"] = req.headers.origin;
headers["Access-Control-Allow-Origin"] = "*";
headers["Access-Control-Allow-Methods"] = "POST, GET, PUT, DELETE, OPTIONS";
headers["Access-Control-Allow-Credentials"] = false;
headers["Access-Control-Max-Age"] = '86400'; // 24 hours
headers["Access-Control-Allow-Headers"] = "X-Requested-With, X-HTTP-Method-Override, Content-Type, Accept";
res.writeHead(200, headers);
res.end();
} else {
//...other requests
}
【讨论】:
else 分支中包含 Allow-Origin 以用于您希望启用 CORS 的请求。要点仅显示如何正确处理 OPTIONS 请求。