Connecting to Node.js Express server using XMLHttpRequest — cors error

  cors, express, javascript, node.js

I’m trying to connect to a node.js express server using a XMLHttpRequest() method, but I keep getting the dreaded cors policy error. How do I enable this?

Every tutorial I’ve been following ends up giving me the same error

CLIENT

window.onload = () => {
    // Create the XHR object.
    function createCORSRequest(method, url) {
        var xhr = new XMLHttpRequest();
        if ("withCredentials" in xhr) {
            // XHR for Chrome/Firefox/Opera/Safari.
            xhr.open(method, url, true);
        } else if (typeof XDomainRequest != "undefined") {
            // XDomainRequest for IE.
            xhr = new XDomainRequest();
            xhr.open(method, url);
        } else {
            // CORS not supported.
            xhr = null;
        }
        return xhr;
    }

    // Helper method to parse the title tag from the response.
    function getTitle(text) {
        return text.match('<title>(.*)?</title>')[1];
    }
    
    // Make the actual CORS request.
    function makeCorsRequest() {
        // This is a sample server that supports CORS.
        var url = 'http://localhost:2000';

        var xhr = createCORSRequest('GET', url);
        if (!xhr) {
        console.log('CORS not supported');
        return;
        }

        // Response handlers.
        xhr.onload = function() {
            var text = xhr.responseText;
            var title = getTitle(text);
            alert('Response from CORS request to ' + url + ': ' + title);
        };

        xhr.onerror = function() {
            console.log('Woops, there was an error making the request.');
        };

        xhr.send();
    }
    
    makeCorsRequest();
}

SERVER

const http      = require('http'),
      path      = require('path'),
      express   = require('express'),
      app       = express(),
      serv      = require('http').Server(app),
      cors      = require('cors');

var corsOptions = {
    origin: '*',
    optionsSuccessStatus: 200 // some legacy browsers (IE11, various SmartTVs) choke on 204
}


var htmlPath = path.join(__dirname, 'client');

app.use(express.static(htmlPath), cors(corsOptions));

app.get('/', cors(corsOptions), (req, res, next) => {
    res.sendFile(htmlPath + '/index.html');
});

var server = serv.listen(2000, () => {
    var host = 'localhost';
    var port = server.address().port;
    console.log(`listening on http://${host}:${port}/`);
});


var io = require('socket.io')(serv,{});
io.sockets.on('connection', (socket) => {
    console.log('Socket connected');
});

Source: Ask Javascript Questions

LEAVE A COMMENT