javascript - 无法创建发布请求
问题描述
我正在尝试向我的服务器发出发布请求,但我无法创建。我必须创建的请求是 -
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>
请帮我解决这个问题。当单击按钮购买它并查看开发人员工具时,我收到了选项请求。我也想发送数据 {"buyId":"3232323-32-3-23-23232-3","force":false,"token":11111111111} 但我无法将其发送到我的服务器。谢谢
解决方案
发生这种情况是因为浏览器作为安全措施会阻止来自两个不同 URL 的请求,例如 www.abc.com 到 www.xyz.com。您可以通过在请求的后端服务器上配置 CORS 来解决此问题,或者测试您可以在浏览器中使用 CORS 插件来解决该问题。例如,在 chrome 中,您可以使用下面的插件来禁用 CORS https://chrome.google.com/webstore/detail/allow-control-allow-origi/nlfbmbojpeacfghkpbjhddihlkkiljbi?hl=en
推荐阅读
- r - model.frame.default 中的错误(公式 = mldata.knn$Gender ~ ., data = mldata_train, : 可变长度不同(为“年龄”找到)
- javascript - 有人能解释一下为什么reduce函数能安慰以下数字吗
- iis-10 - 我无法使用 asp classic 从 IIS(win 2016)生成大于 25.6 MB 的 XML 文件
- python - 为什么 pip 声称我有一个不兼容的模块,尽管版本正确(并破坏了 docker 构建)?
- javascript - 单击html链接时禁用springboot请求检查
- c# - 如果字符串中没有其他文本,C# RegEx 仅替换匹配项
- vue.js - 如何在 Nuxt.js 中编辑 main.js 文件?
- javascript - 将 HTML 表单输入到表格中
- c++ - 如何使用 bazel.rc 指定 c++ 14/17(特定于使用 GCC /G++ 的工具,项目未对其他工具链开放)
- jq - 查询列表输出的 jq 语法帮助