0

I have defined the following express server, which is hosted on localhost:

const express = require('express');
const http = require('http');

var app = express();

app.get('/', function(req, res){
    res.status(200);
    res.send("Hello World");
});


var options = {};
var server = http.createServer(options, app);

server.listen(3000, function(){
    console.log("Start listening on port 3000.")
});

I am trying to send a request to this server via the following html page (which I am opening with Safari):

<!DOCTYPE html>
<html>
    <head>
        <script>
            function request(){
                var req = new XMLHttpRequest();
                req.open('GET', 'http://localhost:3000');
                req.onreadystatechange = function(){
                    alert(req.status);
                    if(req.status === 200){
                       alert(req.responseText);
                    }
                }
                req.send();
            }
        </script>

    </head>
    <body>
        <button onclick="request()">Click</button>
    </body>
</html>

My problem is, that the server does not seem to respond to the request. The status code alert says that I receive status code '0'. Is this a problem due to the fact, that the client page is not hosted through a webserver?

Sebastian Dine
  • 815
  • 8
  • 23
  • 2
    are you loading your html page from the express server? if not, you will need to set a CORS header to allow XMLHttpRequest to access your express server. https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS – ysth Dec 16 '19 at 10:01
  • req.status is 0 before the requests complete. Maybe can you add req.readyState with your status check? `req.readyState === 4 && req.status === 200` More on readyState at https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/readyState – vidu.sh Dec 16 '19 at 10:07
  • could you try `req.addEventListener("load", yourFunction);` and `function yourFunction() { console.log(this); }` (simple snippet taken from here: https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Using_XMLHttpRequest) – GrafiCode Dec 16 '19 at 10:10
  • Open the developer tools. Look at the console. **Read the error messages** – Quentin Dec 16 '19 at 10:19
  • setting CORS header in the response did the job. – Sebastian Dine Dec 16 '19 at 13:34

0 Answers0