我第一次尝试使用 Node.js 尝试将参数从表单传递到我的服务器并在控制台上打印它们
我的 html
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Hello Node</title>
</head>
<body>
<h1> we have a website</h1>
<form action="/contact" enctype="application/json" method="POST">
<input name="firstName" placeholder="firstName" type="text" size="30" />
<input name="lastName" placeholder="lastName" type="text" size="30" />
<input name="submit" type="submit" value="Send This">
</form>
</body>
</html>
- 我试过有无
enctype="application/json"
我的 app.js 文件
const express = require('express');
const app = express();
const bodyParser = require('body-parser')
var jsonParser = bodyParser.json()
app.listen(3333, () => {
console.log("Server is up and listening on 3003"); //print to the server console (the terminal!!)
})
app.post("/contact", jsonParser, function (req, res) {
console.log("in /contact");
console.log("request body:" + req.body);
console.log("request body first name:" + req.body.firstName);
console.log("request query first name:" + req.query.firstName);
})
- 我试过有无
app.use(bodyParser.json({ type: 'application/*+json' }))
输出:
[对象对象]
请求正文名字:未定义
请求查询名字:未定义