我有一个运行在 localhost:3000
的 Node (快速)服务器。另一方面,我有一个由服务器本身提供的 HTML (client.html
) 文件,在路径 /client
上(该文件作为响应发送) .
我的目标是在 client.html
页面(由同一服务器提供服务)上使用 AJAX 调用访问另一条路径,即 /test
。但是,从帖子中可以明显看出,它不起作用。
不重复:到目前为止,我已经尝试了以下 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 上。
问题在哪里和/或什么地方?
最佳答案
我尝试使用您的客户端代码(在我添加缺少的 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 以查看您实际返回的 header - curl -I localhost:3000
。
关于javascript - Ajax 不向同一端口上的本地主机发送请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57336223/