javascript - 没有带有标题的“Access-Control-Allow-Origin”
问题描述
我有一个可以工作的 HTTPS 服务器,我正在尝试向客户端返回答案。我能够从客户端发送 GET 请求,但是当我从服务器返回响应时,我继续收到此错误:
无法加载https://localhost:8000/?uname=user&upass=pass:对预检请求的响应未通过访问控制检查:请求的资源上不存在“Access-Control-Allow-Origin”标头。因此,不允许访问源“ http://localhost:63342 ”。
我究竟做错了什么?
这是我的服务器:
var https = require('https');
var fs = require('fs');
var options = {
key: fs.readFileSync('key.pem'),
cert: fs.readFileSync('cert.pem')
};
https.createServer(options, function (req, res) {
res.write('Hello World!'); //write a response to the client
res.end(); //end the response
}).listen(8000);
这是我的客户:
const xhr = new XMLHttpRequest();
xhr.onreadystatechange = function () {
if (xhr.readyState === XMLHttpRequest.DONE) {
console.log(xhr.responseText);
}
};
xhr.open('GET', `https://localhost:8000?uname=${user}&upass=${pass}`,true);
xhr.setRequestHeader("Access-Control-Allow-Origin","*");
xhr.setRequestHeader("Access-Control-Allow-Headers","Content-Type");
xhr.setRequestHeader("Access-Control-Allow-Methods","GET,POST,PUT,DELETE,OPTIONS");
xhr.setRequestHeader("ccess-Control-Allow-Credentials","true");
xhr.send();
解决方案
在服务器上尝试这个,在你的createServer
处理程序中,之前res.end()
:
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Access-Control-Request-Method', '*');
res.setHeader('Access-Control-Allow-Methods', 'OPTIONS, GET, PUT, PATCH, DELETE');
res.setHeader('Access-Control-Allow-Headers', 'authorization, content-type');
推荐阅读
- jquery - 通过 .blur jquery 访问每个类元素并将其发送到控制器
- scala - scalafmt 类,方法参数意图
- python - 如何根据另一个数组中的值从初始数据中删除特定行?
- ios - Dismiss 使跳转视图控制器 Swift
- java - 如何在硒中模拟真正的按键输入动作?
- c# - BackgroundService 中的阻塞调用使另一个 BackgroundService 无法运行
- python - Beautiful Soup 网页抓取:我如何抓取这个特定的 html 结构
- r - 如何为 R 中的 plm(池)模型计算 stargazer 中的稳健标准误差?
- tcl - TCL 脚本打印带有特定模式的字符串
- linux - Kubernetes 在容器中隐式使用 Nvidia 文件