【发布时间】:2020-11-15 03:19:07
【问题描述】:
我正在运行 express.js 本地服务器。它正在发送一个 html 文件,如果我按下一个按钮,它将调用服务器端 api 并获得结果。但似乎 $.post 将空正文 ({}) 发送到服务器。
服务器端代码
const express = require('express');
const bodyParser = require('body-parser');
const app = express();
// create application/json parser
var jsonParser = bodyParser.json()
// create application/x-www-form-urlencoded parser
var urlencodedParser = bodyParser.urlencoded({ extended: false })
app.get('/', function(req, res) {
console.log(req.hostname);
res.sendFile(`${__dirname}/index.html`);
});
app.post("/", urlencodedParser, function(req, res) {
console.log(req.body);
res.send(`The sum is ${Number(req.body.num1) + Number(req.body.num2)}`);
});
app.post("/api/sum", jsonParser, function(req, res) {
console.log(req.body);
res.send({ data: "success" });
});
app.listen(3000, function() {
console.log("server started at port 3000");
});
HTML 文件
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Calculator</title>
</head>
<body>
<h1>Calculator</h1>
<form action="/" method="POST">
<input type="text" name="num1" placeholder="first number" id="num1">
<input type="text" name="num2" placeholder="second number" id="num2">
<button type="submit" name="submit">submit</button>
</form>
<button id="noRefresh">No refresh update</button>
</body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
$("#noRefresh").click(function() {
console.log("posting " + $("#num1").val() + " " + $("#num2").val());
$.post("/api/sum", {
num1: $("#num1").val(),
num2: $("#num2").val()
},
function(data, status) {
alert("The sum is " + data.data);
});
});
</script>
</html>
当我按下“不刷新更新”按钮时,我在服务器端收到 {} 空对象。怎么了?
【问题讨论】:
标签: jquery node.js express body-parser