No' Access-Control-Allow-Origin'标题

时间:2018-06-07 15:18:44

标签: javascript https

我有一台HTTPS服务器可以工作,我试图回复客户端的答案。我能够从客户端发送GET请求,但是当我从服务器返回响应时,我仍然会收到此错误:

  

无法加载https://localhost:8000/?uname=user&upass=pass:响应   预检请求没有通过访问控制检查:否   '访问控制允许来源'标题出现在请求的上   资源。起源' 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();

1 个答案:

答案 0 :(得分:3)

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');