【发布时间】:2019-12-11 15:45:45
【问题描述】:
我有一个在localhost:3000 运行的节点(快速)服务器。另一方面,我有一个由服务器本身提供的 HTML (client.html) 文件,位于路由 /client 上(该文件作为响应发送)。
我的目标是访问另一条路线,即/test,在client.html 页面上使用AJAX 调用(由同一台服务器提供服务)。但是,从帖子中可以明显看出,它不起作用。
不重复:到目前为止,我已经尝试了以下 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>
我尝试发送GET 和POST 请求,但都没有成功。
我以前做过这个,只是没有nodejs。当我使用requests 库从Python 脚本发送请求时,会收到响应,因此服务器似乎 工作得很好。
仅供参考,我在 Windows 上。
问题在哪里和/或在哪里?
【问题讨论】:
-
请在您的
/test路线中与console.log(req.body)核对 -
你为什么要发送 CORS 标头?没必要
-
@JaromandaX 是的,但那时我几乎可以尝试任何事情......\
-
您是否尝试过使用
res.end()来表示响应的结束? -
@JaromandaX 是的。
res.end()产生了相同的结果。
标签: javascript node.js ajax