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?