为什么将JSON参数从HTML传递到Node.js会导致body参数未定义
我第一次尝试使用Node.js将参数从表单传递到服务器,并在控制台上打印它们 我的html为什么将JSON参数从HTML传递到Node.js会导致body参数未定义,node.js,json,html-post,Node.js,Json,Html Post,我第一次尝试使用Node.js将参数从表单传递到服务器,并在控制台上打印它们 我的html <!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Hello Node</title>
<!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>
- 我试过使用和不使用app.use(bodyParser.json({type:'application/*+json'}))
application/json未定义的内容类型不允许设置为enctype值,因此您可以使用javascript发送json,或者通过app.use(bodyParser.urlencoded({extended:false})添加对application/x-www-form-urlencoded的支持
bodyParser.urlencoded——我认为在URL字符串中传递参数时需要使用它,即:/contact/?firstname:“kukula”
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);
})