Ajax不在同一端口上向本地主机发送请求

时间:2019-08-03 07:06:13

标签: javascript node.js ajax

我有一个运行在localhost:3000上的节点(快速)服务器。另一方面,我有一个HTML(client.html)文件,该文件由服务器本身在路线/client上提供服务(该文件作为响应发送)。

我的目标是在/test页面(由同一服务器提供服务)上使用AJAX调用访问另一条路由,即client.html。但是,从帖子中可以很明显地看出来,它不起作用。

不是重复的:到目前为止,我已经尝试了以下SO帖子中给出的解决方案,但没有成功:

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?

这是我的源代码。

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>

我尝试发送GETPOST请求,但是都没有。

我以前已经这样做过,只是没有使用nodejs。当我使用requests库从 Python 脚本发送请求时,收到了响应,因此服务器似乎可以正常工作。

仅供参考,我在Windows上。

问题出在哪里和/或什么地方?

1 个答案:

答案 0 :(得分:1)

我尝试了您的客户端代码(在我添加了缺失的jquery导入之后),以下代码似乎运行良好(我没有使用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();
});

我建议在终端上运行curl以查看实际上返回的标头-curl -I localhost:3000