2016-09-21 60 views
0

内URL如果我的权利,通过浏览器的地址栏来访问服务器,服务器成功响应。 但当我尝试从我send.js访问它脚本:CORS:策略不同,如果从浏览器或访问脚本

var request = new XMLHttpRequest(); 
request.open('GET', "myserver.com", true); 
request.setRequestHeader("Content-type", "application/x-www-form-urlencoded;charset=UTF-8;"); 
request.onreadystatechange = function() 
{ 
    document.write("received response: " + request.response); 
}; 
document.write("sending request ..."); 
request.send('login=billy&password=sunshines'); 

用浏览器访问它通过的index.html在猫鼬本地Web服务器:

<!DOCTYPE html> 
<html> 
<head> 
    <meta charset="utf-8"> 
    <title>Server send script TEST</title> 
</head> 
<body> 
<script src="send.js"></script> 
</body> 

它失败,错误:否请求的资源上存在“Access-Control-Allow-Origin”标头。因此,'http://192.168.0.101:8080'不允许访问。

为什么CORS当我直接访问网页通过浏览器的地址栏中,从当我通过本地托管脚本访问策略不同?我是否缺少一些字段来指定请求?

回答

2

当您直接通过地址栏访问脚本没有跨源资源共享的发生。您的浏览器导航到myserver.com所以myserver.com任何要求是相同的起源。

当您的浏览器位置是http://192.168.0.101:8080时,对于myserver.com的请求是跨源,因为您的浏览器位置与您发出http请求的位置不同。

您必须启用后端CORS或使用JSONP。