1

I have a node (express) server running at localhost:3000. On another hand, I have an HTML (client.html) file which is served by the server itself, on the route /client (the file is sent as the response).

My goal here is to access another route, namely /test using an AJAX call on the client.html page (WHICH IS SERVED BY THE SAME SERVER). However, as it's quite obvious from the post, it isn't working.

Not a duplicate: I have tried the solutions given in the following SO posts, so far, without success:

jQuery Ajax request from local filesystem (Windows file:///) - though
ajax call not working when trying to send data to localhost:8000 from localhost
Why doesn't adding CORS headers to an OPTIONS route allow browsers to access my API?

Here are my source codes.

server.js

const express = require("express")
const bodyParser = require("body-parser")

var app = express()
app.use(bodyParser.urlencoded({extended:false}));
app.use(bodyParser.json())
...
app.get('/', (req, res)=>{
    res.setHeader('Access-Control-Allow-Origin', '*')
    res.send('This server does not support GET requests.')
})

app.post('/test', (req, res)=>{
    res.setHeader('Access-Control-Allow-Origin', '*')
    res.send("response from /test")
})

var port = 3000
var server = app.listen(port)

client.html

<html>
    <script src="https://code.jquery.com/jquery-3.4.1.slim.min.js"></script>
    <script>
        function init(){
            $.ajax({
                url: 'http://127.0.0.1:3000/test',
                method: 'POST',
                contentType: 'application/x-www-form-urlencoded'
            }).done((data)=>{
                alert(data);
            });
        }
    </script>
    <body onload="javascript:init()">
    </body>
</html>

I have tried sending both a GET and a POST request but none of them worked.

I have done this before, only not with nodejs. When I send a request from a Python script, using the requests library, the response is received, so the server seems to work just fine.

FYI, I'm on Windows.

Where and/or what is the issue in?

progyammer
  • 1,498
  • 3
  • 17
  • 29
  • Please check with `console.log(req.body)` in your `/test` route – Nathan Fries Aug 03 '19 at 07:10
  • 1
    why are you sending CORS headers at all? no need for that – Jaromanda X Aug 03 '19 at 07:12
  • @JaromandaX Yeah but I'm at that point rn that I'd try almost anything ...\ – progyammer Aug 03 '19 at 07:13
  • have you tried using `res.end()` to signify the end of the response? – Jaromanda X Aug 03 '19 at 07:13
  • @JaromandaX Yes. `res.end()` produced the same results. – progyammer Aug 03 '19 at 07:14
  • what do you observe in your browsers development tools console / network tab regarding the request? – Jaromanda X Aug 03 '19 at 07:15
  • @NathanFries I just checked with `console.log(..)`. Nothing is shown when the HTML page is supposed to have made an AJAX call. – progyammer Aug 03 '19 at 07:16
  • Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/197418/discussion-between-progyammer-and-jaromanda-x). – progyammer Aug 03 '19 at 07:18
  • So the client is not making the call. Try using `/test` as the complete `url` in the ajax call – Nathan Fries Aug 03 '19 at 07:19
  • Three points: 1. Since `GET` requests are not supported how you are getting client.html from `localhosat:3000`? 2. Secondly, can you just try POST to `/test` endpoint instead of the complete URL? 3. Unless these resources are not from same host and port you'll face issues but I see you are allowing CORS. – fiveelements Aug 03 '19 at 07:38
  • @fiveelements GET requests **are** supported, as I have defined the get handler for that route. I am just sending out a message to whoever accesses the root (since there's nothing to do on the root) – progyammer Aug 03 '19 at 07:57

1 Answers1

1

I tried with your client code (after I added missing jquery import) following which seems to work well (I havent use express):

const server = http.createServer(function (req, res) {
    console.log("logging stuff")
    res.setHeader('Access-Control-Allow-Origin', '*')
    res.write('This server does not support GET requests.')
    res.end();
});

I would suggest to run curl on your terminal to see what headers you actually get back - curl -I localhost:3000.

Pavel Schoffer
  • 492
  • 1
  • 3
  • 11