首页 > 解决方案 > 没有带有标题的“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();

标签: javascripthttps

解决方案


在服务器上尝试这个,在你的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');

推荐阅读