我正在尝试向(我拥有的) WCF服务发出跨域HTTP请求。我已经阅读了几种处理跨域脚本限制的技术。因为我的服务必须同时支持GET和POST请求,所以我不能实现一些src是GET请求的URL的动态脚本标记。由于我可以自由地在服务器上进行更改,因此我已经开始尝试实现一种变通方法,其中包括配置服务器响应以包含"Access-Control-Allow-Origin“标头和带有和OPTIONS请求的”印前检查“请求。我是从这篇文章中得到这个想法的:Getting CORS working
在服务器端,我的web方法将“Access-Control-Allow-Origin:*”添加到HTTP响应中。我可以看到响应现在确实包含了这个头。我的问题是:我如何‘预检’一个请求(选项)?我正在使用jQuery.getJSON发出GET请求,但浏览器立即取消了该请求,并显示了声名狼藉的代码:
访问-控制-允许-原始地址不允许
源地址http://localhost
有人熟悉这种CORS技术吗?需要在客户端进行哪些更改才能对我的请求进行预检?
谢谢!
发布于 2012-01-01 00:55:26
在印前检查请求过程中,您应该会看到以下两个头部: Access-Control- request -Method和Access-Control-Request-Headers。这些请求标头向服务器请求进行实际请求的权限。您的印前检查响应需要确认这些标头,才能使实际请求正常工作。
例如,假设浏览器发出具有以下标头的请求:
Origin: http://yourdomain.com
Access-Control-Request-Method: POST
Access-Control-Request-Headers: X-Custom-Header然后,您的服务器应使用以下标头进行响应:
Access-Control-Allow-Origin: http://yourdomain.com
Access-Control-Allow-Methods: GET, POST
Access-Control-Allow-Headers: X-Custom-Header请特别注意Access-Control-Allow-Headers响应头。此标头的值应与Access-Control- request -Headers请求标头中的标头相同,并且不能为'*‘。
将此响应发送到印前检查请求后,浏览器将发出实际请求。你可以在这里了解更多关于CORS的信息:http://www.html5rocks.com/en/tutorials/cors/
发布于 2017-08-24 13:59:16
虽然这个帖子可以追溯到2014年,但这个问题对我们中的许多人来说仍然是最新的。以下是我在jQuery 1.12 /PHP 5.6上下文中处理它的方式:
PHP代码示例:
if (!empty($_SERVER['HTTP_ORIGIN'])) {
// Uh oh, this XHR comes from outer space...
// Use this opportunity to filter out referers that shouldn't be allowed to see this request
if (!preg_match('@\.partner\.domain\.net$@'))
die("End of the road if you're not my business partner.");
// otherwise oblige
header("Access-Control-Allow-Origin: " . $_SERVER['HTTP_ORIGIN']);
}
else {
// local request, no need to send a specific header for CORS
}特别是,不要添加exit;,因为不需要任何印前检查。
发布于 2021-08-17 11:10:34
通过以下简单的步骤在Node.js中编写您的自定义中间件来解决CORS问题。
don't need to set anything from the client, just a little change on the Node.js server will fix the problem.
创建中间件:
// in middleware/corsResolver.js
function corsResolver(req, res, next) {
// Website you wish to allow to connect
// running front-end application on port 3000
res.setHeader('Access-Control-Allow-Origin', 'http://localhost:3000');
// 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,Authorization');
// 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();
}
module.exports = corsResolver;现在编辑您的server.js (index.js或启动节点服务器的任何主文件),并添加此中间件:
// server.js or indes.js
const corsResolver = require('path/to/resolver-middleware')
app.use(corsResolver) // -----------> applied middleware here
// other stuffhttps://stackoverflow.com/questions/8685678
复制相似问题