Javascript CORS:如果从浏览器或脚本中访问URL,则策略不同
若我通过浏览器的地址字段访问服务器,服务器将成功响应。 但是当我尝试从我的send.js脚本访问它时:Javascript CORS:如果从浏览器或脚本中访问URL,则策略不同,javascript,http,get,cors,Javascript,Http,Get,Cors,若我通过浏览器的地址字段访问服务器,服务器将成功响应。 但是当我尝试从我的send.js脚本访问它时: var request = new XMLHttpRequest(); request.open( 'GET', "myserver.com", true ); request.setRequestHeader("Content-type", "application/x-www-form-urlencoded;charset=UTF-8;"); request.onreadystatecha
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' );
使用浏览器通过Mongoose本地web服务器通过index.html访问:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Server send script TEST</title>
</head>
<body>
<script src="send.js"></script>
</body>
服务器发送脚本测试
失败,错误为:请求的资源上不存在“访问控制允许来源”标头。因此,不允许对源“”进行访问。
为什么直接通过浏览器的地址字段访问页面和通过本地托管脚本访问页面时CORS策略不同?我是否缺少一些要为请求指定的字段?当您使用地址栏直接访问脚本时,不会发生跨源资源共享。您的浏览器已导航到
myserver.com
,因此对myserver.com
的任何请求都是相同的来源
当您的浏览器位置为http://192.168.0.101:8080
,对myserver.com
的请求是跨源的,因为您的浏览器位置与您发出http请求的位置不同
您必须在后端启用CORS或使用JSONP。当您使用地址栏直接访问脚本时,不会发生跨源资源共享。您的浏览器已导航到
myserver.com
,因此对myserver.com
的任何请求都是相同的来源
当您的浏览器位置为http://192.168.0.101:8080
,对myserver.com
的请求是跨源的,因为您的浏览器位置与您发出http请求的位置不同
您必须在后端启用CORS或使用JSONP