使用 Ajax 将数据从 HTML 发送到节点 Js

Sending data from HTML to node Js with Ajax

提问人:Adnan Sen 提问时间:6/12/2023 最后编辑:BatuhanAdnan Sen 更新时间:6/13/2023 访问量:39

问:

我有一个HTML页面,想将一个数组发送到Nodejs服务器,称为output_list。Html 和 Js 文件,Nodejs 在 Macbook Pro 上本地运行。

我的HTML代码:

$.ajax({
    url: '/',
    type: 'POST',
    contentType: false,
    dataType: "json",
    data: {output_list: JSON.stringify(output_list)},
    success: function (res) {console.log("Output list transferred successfully") },
    error: function (err) { console.log("Transfer is not successful") },
}); 

我在 NodeJs 的 Js 文件上的代码:

const express = require("express");
const bodyParser = require("body-parser");

const app = express();
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());

app.get("/", function (req, res) {
    res.sendFile(__dirname + "/Router36x36.html");
});

app.post("/", function (req, res) {
    res.status(200).send(output_list.toString());
    res.send("Thanks for posting these");
});

app.listen(3000, function (req, res) {
    console.log("Server is running on port 3000");
});

我总是收到 405 错误代码。

POST http://127.0.0.1:5500/ 405(不允许使用方法)

路由器36x36.html:1114 传输不成功。

如果您帮助我解决这个问题,我将不胜感激。 谢谢 阿德南·森

我尝试了很多东西,但找不到方法。

JavaScript 节点 .js JSON ajax

评论

1赞 Quentin 6/12/2023
“Router36x36.html:1114 传输不成功。” — 该文件的 URL 应该是浏览器不应该知道 Router36x36.html。很有可能您错误地加载了 HTML 文档,而不是错误地加载了 HTML 文档。/file:///http://loalhost:3000/
0赞 Quentin 6/12/2023
const bodyParser=require("body-parser");— Express 依赖于 body-parser 并通过 expressjs.com/en/api.html#express.urlencoded 等方式公开它。无需显式包含 body-parser。
1赞 The KNVB 6/13/2023
您的服务器正在侦听端口 3000,而不是 5500。
0赞 Adnan Sen 6/13/2023
你能给我写 Nodejs 端的代码吗?我已经更改了我的 JQuery 代码,如下所示。$.ajax({ url: '/localhost:3000', type: 'POST', data: { json: JSON.stringify({cikis_listesi}) }, dataType: 'json', success: function (res) { console.log(“输出列表传输成功”) }, error: function (err) { console.log(“传输未成功”) } });

答: 暂无答案