js跨域访问,No 'Access-Control-Allow-Origin' header is present on the requested resource

2023-02-15,,,,

js跨域访问提示错误:XMLHttpRequest cannot load http://...... No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access.

解决方法:

1、如果请求的url是aspx页面,则需要在aspx页面中添加代码:Response.AddHeader("Access-Control-Allow-Origin", "*");

2、如果请求的url是PHP页面,则需要在PHP页面中添加代码:header("Access-Control-Allow-Origin: *");【本人使用的php,用此方法问题得以解决】

3、如果请求的url是静态的html页面,则需要在页面中添加meta标签代码:<meta http-equiv="Access-Control-Allow-Origin" content="*" />

如果服务器端可以确定是要被哪些域名访问,最好是能把以上代码中的“*”代替为具体的域名,这样做可以相应的增强安全性。

=====================================

最新的W3C标准里是这么实现HTTP跨域请求的, Cross-Origin Resource Sharing

简单的来说,就是跨域的目标服务器要返回一系列的Headers,通过这些Headers来控制是否同意跨域。这些Headers有:4 Syntax

4.1 Access-Control-Allow-Origin HTTP Response Header

4.2 Access-Control-Max-Age HTTP Response Header

4.3 Access-Control-Allow-Credentials HTTP Response Header

4.4 Access-Control-Allow-Methods HTTP Response Header

4.5 Access-Control-Allow-Headers HTTP Response Header

4.6 Origin HTTP Request Header

4.7 Access-Control-Request-Method HTTP Request Header

4.8 Access-Control-Request-Headers HTTP Request Header

在 Request 包和 Response 包中都有一些。

其中最敏感的就是 Access-Control-Allow-Origin 这个 Header, 他是W3C标准里用来检查该跨域请求是否可以被通过。 (Access Control Check)

跨域实现的过程大致如下:

从 http://www.a.com/test.html 发起一个跨域请求,

请求的地址为: http://www.b.com/test.php

如果 服务器B返回一个如下的header

Access-Control-Allow-Origin: http://www.a.com

那么,这个来自 http://www.a.com/test.html 的跨域请求就会被通过。

=======================

原文链接:http://zjblogs.com/js/Access-Control-Allow-Origin.html

js跨域访问,No 'Access-Control-Allow-Origin' header is present on the requested resource的相关教程结束。

《js跨域访问,No 'Access-Control-Allow-Origin' header is present on the requested resource.doc》

下载本文的Word格式文档,以方便收藏与打印。