-1

I have an HTTPS server thah works, I'm trying to return an answer to the client. I am able to send a GET request from the client, but when I return a response from the server, I continue to get this error:

Failed to load https://localhost:8000/?uname=user&upass=pass: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:63342' is therefore not allowed access.

What am I doing wrong?

this is my server:

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

and this is my client:

    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();
user8446864
  • 105
  • 1
  • 9

1 Answers1

3

Try this on the server, inside your createServer handler, before 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');
ouni
  • 3,233
  • 3
  • 15
  • 21