[英]Request urlencoded body is empty in express
I'm trying to get url parameters in express 4.17.3 using the urlencoded middleware but the body is always empty, I reproducted it to a minimal code:我正在尝试使用 urlencoded 中间件在 express 4.17.3 中获取 url 参数,但正文始终为空,我将其重新生成为最小代码:
const express = require("express");
(()=>{
const app = express();
app.use(express.urlencoded());
app.get("/", async(req, res)=>{
console.log(req.body); //always print '{}'
res.send();
});
app.listen(83, ()=>{
console.log("test app listening on port 83");
})
})();
Here's my request这是我的要求
http://localhost:83/?param1=42
What am I doing wrong?我究竟做错了什么?
A few things to break down.有几件事要分解。 To answer your question to get params you can use
req.query
so your code would be:要回答您的问题以获取参数,您可以使用
req.query
因此您的代码将是:
app.get('/', async (req, res) => {
console.log(req.query)
res.send()
})
Addressing urlencoded
it should be changed from:寻址
urlencoded
它应该从:
app.use(express.urlencoded());
to:到:
app.use(express.urlencoded({ extended: true }))
good habit to not hard code the port
so the line of code:不要硬编码
port
的好习惯,所以代码行:
app.listen(83, ()=>{
console.log("test app listening on port 83");
})
should be:应该:
const PORT = process.env.PORT || 83
app.listen(PORT, () => {
console.log(`test app listening on port ${PORT}`)
})
full working code example:完整的工作代码示例:
const express = require('express')
const app = express()
app.use(express.urlencoded({ extended: true }))
const PORT = process.env.PORT || 83
app.get('/', async (req, res) => {
console.log(req.query)
res.send()
})
app.listen(PORT, () => {
console.log(`test app listening on port ${PORT}`)
})
When using express I also like to implement nodemon
and if you add this to your package.json :使用 express 时,我也喜欢实现
nodemon
,如果将其添加到package.json 中:
"dev": "nodemon node index.js"
then in the terminal you can run:然后在终端中你可以运行:
npm run dev
you wont have to restart your server during development changes.在开发更改期间,您不必重新启动服务器。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.