[英]node.js body-parser bad interpretation of Content-Type:x-www-form-urlencoded and Form-data JSON
[英]How to change Content-Type: appication/x-www-form-urlencoded to application/json?
我正在尝试表达用户注册的意愿。 我先制作了后端,由于我使用邮递员对其进行了验证,因此似乎工作正常。 在邮递员中,我将Content-Type作为application / json包含在内,并将json数据包含在原始数据标签中。 但是,在制作表单(名称,电子邮件,密码)时,我无法将此后端实现为前端。 即使出现错误,我仍然无法包含姓名,电子邮件和密码。 我试图console.log req.body并得到空数组。 但是,在Chrome的网络标签中,名称,电子邮件和密码包含在表单数据中。 我认为问题不在于body-parser,因为邮递员没有任何问题。 在网络标签中,我看到请求的Content-Type: application/x-www-form-urlencoded
为Content-Type: application/x-www-form-urlencoded
而不是application/json
,我认为这可能是导致错误的原因。
server.js
app.use(express.json({ extended: false }));
app.get('/register', (req, res) => res.render('register'));
app.use('/api/users', require('./routes/api/users'));
API / users.js
// @ route POST api/users
// @desc Register User
// @access Public
router.post(
'/',
[
check('name', 'Name is required')
.not()
.isEmpty(),
check('email', 'Please include a valid email').isEmail(),
check(
'password',
' Please enter a password with 6 or more characters'
).isLength({ min: 6 })
],
async (req, res) => {
const errors = validationResult(req);
if (!errors.isEmpty()) {
console.log(req.body);
return res.status(400).json({
errors: errors.array()
});
}
const { name, email, password } = req.body;
.
.
.
register.handlebars
<form class="form" action="/api/users" method="post">
<div class="form-group">
<input name="name" type="text" placeholder="Name" requried>
</div>
<div class="form-group">
<input name="email" type="email" placeholder="E-mail">
</div>
<div class="form-group">
<input name="password" type="text" placeholder="Password" minlength="6">
</div>
<input type="submit" value="Create account" class="button green-button" />
</form>
express.json()
是用于解析Content-Type: application/json
数据的解析器Content-Type: application/json
。 您在代码中使用它,这就是它在Postman中工作的原因。 为了解析编码为application/x-www-form-urlencoded
,您只需要添加另一个解析器,在本例中为express.urlencoded()
。 另外, urlencoded()
而不是json()
接受extended
选项。
app.use(express.json()) // parses application/json
app.use(express.urlencoded({ extended: true })) // parses application/x-www-form-urlencoded
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.