Ajax not sending request to localhost on same port

旧城冷巷雨未停 提交于 2021-02-05 08:08:43

问题


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?


回答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.



来源:https://stackoverflow.com/questions/57336223/ajax-not-sending-request-to-localhost-on-same-port

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!