【发布时间】:2018-11-17 13:59:39
【问题描述】:
我有一个可以工作的 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();
【问题讨论】:
-
访问控制标头必须在来自服务器的响应中,而不是来自客户端的请求。
-
那么我该如何添加它们呢?
-
res.writeHead()还是什么?我没有记住整个节点 API。 -
解决方法是在错误信息的第一个谷歌结果中。
-
您需要对正在使用的服务器的 CORS 进行一些研究。这是一个类似的问题 - stackoverflow.com/questions/7067966/how-to-allow-cors,可能会帮助您走上正轨。
标签: javascript https