Javascript Can';不要创建post请求
我试图向我的服务器发出post请求,但无法创建。 我必须创建的请求是-Javascript Can';不要创建post请求,javascript,html,post,cors,Javascript,Html,Post,Cors,我试图向我的服务器发出post请求,但无法创建。 我必须创建的请求是- POST /buy/new/product HTTP/1.1 Host: foo.com User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:64.0) Gecko/20100101 Firefox/64.0 Accept: application/json;api-version=3.2- preview.1;excludeUrls=true;e
POST /buy/new/product HTTP/1.1
Host: foo.com
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:64.0)
Gecko/20100101 Firefox/64.0
Accept: application/json;api-version=3.2-
preview.1;excludeUrls=true;enumsAsNumbers=true
;msDateFormat=true;noArrayWrap=true
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
Referer: https://foo2.com/buy/
content-type: application/json
origin: https://foo.com
Content-Length: 76
Connection: close
Cookie: xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
{"buyId":"3232323-32-3-23-23232-3","force":false,"token":11111111111}
但我根据我的守则提出的要求是——
OPTIONS /buy/new/product HTTP/1.1
Host: foo.com
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:64.0)
Gecko/20100101 Firefox/64.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
Access-Control-Request-Method: POST
Access-Control-Request-Headers: content-type
Referer: http://foo.com/
Origin: http://foo.com
Connection: close
我所使用的守则—
<html>
<body>
<center>
<h2>Buy Now</h2>
<div id="demo">
<button type="button" onclick="buy()">Buy Now</button>
</div>
<script>
function buy() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("demo").innerHTML = alert(this.responseText);
}
};
xhttp.open("POST", "https://foo.com//buy/new/product", true);
xhttp.withCredentials = true;
xhttp.setRequestHeader("Content-Type","application/json;api-version=3.2-
preview.1");
xhttp.send(JSON.stringify('{"buyId":"3232323-32-3-23-23232-
3","force":false,"token":11111111111}'));
}
</script>
</body>
</html>
立即购买
立即购买
功能购买(){
var xhttp=newXMLHttpRequest();
xhttp.onreadystatechange=函数(){
if(this.readyState==4&&this.status==200){
document.getElementById(“demo”).innerHTML=alert(this.responseText);
}
};
xhttp.open(“POST”https://foo.com//buy/new/product“,对);
xhttp.withCredentials=true;
setRequestHeader(“内容类型”,“应用程序/json;api版本=3.2-
预览(第1条);
xhttp.send(JSON.stringify(“{”buyId):“3232323-32-3-23-23232-
3、“强制”:假,“标记”:11111}');
}
请帮我解决这个问题。当点击按钮购买它并查看开发者工具时,我得到了选项请求。我还想发送数据{“buyId”:“3232323-32-3-23-23232-3”,“force”:false,“token”:11111}
但我无法将此发送到我的服务器。
感谢之所以会发生这种情况,是因为如果请求来自两个不同的URL(例如www.abc.com到www.xyz.com),作为安全性的浏览器会阻止请求。您可以通过在您请求的后端服务器上配置CORS来解决此问题,或者为了测试,您可以在浏览器中使用CORS插件来解决此问题。例如,在chrome中,您可以使用下面的插件禁用CORS
除非其他服务器允许,否则无法向其发出请求。上述脚本是否托管在“foo.com”上?还是你自己的服务器?选项请求是一种飞行前请求,用于检查发送实际请求是否会失败。另外,为什么要
JSON.stringify
ing字符串?