gpt4 book ai didi

javascript - CORS:如果从浏览器或从脚本内访问 URL,策略会有所不同

转载 作者:行者123 更新时间:2023-12-02 14:10:39 25 4
gpt4 key购买 nike

如果我通过浏览器的地址字段直接访问服务器,服务器会成功响应。但是当我尝试从我的 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.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>

失败并出现错误:请求的资源上不存在“Access-Control-Allow-Origin” header 。来源'http://192.168.0.101:8080 ' 因此不允许访问。

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

最佳答案

当您使用地址栏直接访问脚本时,不会发生跨源资源共享。您的浏览器导航到 myserver.com,因此对 myserver.com 的任何请求都是同源的。

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

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

关于javascript - CORS:如果从浏览器或从脚本内访问 URL,策略会有所不同,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39622538/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com