繁体   English   中英

快递:空 req.body

[英]Express: empty req.body

我有简单的快递服务器:

 const express = require('express'); const exphbs = require('express-handlebars'); const path = require('path'); const bodyparser = require('body-parser'); const app = express(); const hbs = exphbs.create({ defaultLayout: 'main', extname: 'hbs' }); const _PORT = process.env.PORT || 80; app.engine('hbs', hbs.engine); app.set('view engine', 'hbs'); app.set('views', 'views'); app.use(bodyparser.urlencoded({ extended: false })); app.use(bodyparser.json({ type: 'application/*+json' })); app.use(express.static(path.join(__dirname, 'public'))); app.use(require('./routers/login')); serverStart(); async function serverStart(){ try{ app.listen(_PORT); console.log('[SERVER] Server is listening port ' + _PORT + ' now.'); }catch(error){ console.log(error); } }

和简单的路由器:

 const { Router } = require('express'); const router = Router(); router.get('/', async (req, res) => { res.render('login', { title: 'main page' }); }); router.post('/', async (req, res) => { console.log(req.body); }); module.exports = router;

为什么“req.body”总是空的? 我试图从“邮递员”发送 POST 查询,但它不起作用。 它仅适用于 x-www-form-urlencoded 查询,但我想发送 json 查询。

PS对不起我的英语。

UPD:邮递员截图链接

我一直在尝试你的代码,它工作正常,你只需要改变你的代码:

app.use(bodyparser.json({ type: 'application/*+json' }));

使用以下代码:

app.use(bodyparser.json({ type: 'application/json' }));

注意:如果您使用的是最新版本的express ,那么您不应该安装body-parser ,因为body-parser已经包含在内。

因此,您可以在下面使用此代码:

app.use(express.json());
app.use(express.urlencoded({ extended: false }));

我希望它能帮助你。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM