在nodejs写接口时 前端使用post请求 但是获取不到请求的参数,获取参数的方法如下:
方法1:模块body-parser,它用于解析客户端请求的body中的内容,内部使用JSON编码处理,url编码处理以及对于文件的上传处理
使用方法:入口文件index.js
import bodyParser from 'body-parser'
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({ extended: false }));
在路由文件里直接访问:
req.body
方法2:模块formidable 这个用于解析请求数据 请求文件
使用方法如下:
安装 yarn add formidable
在路由文件里使用:
import formidable from 'formidable'
//路由处理函数中使用:
const form = formidable.IncomingForm()
form.parse(req, async (err, fields, file) => {
let {user_id}= req.params
})
特别注意: 这两种方法不能同时使用 否则会出现获取不到参数或者报不知名错误的情况 ,谨慎两个一起使用!
在写这段代码时候报的错如下,记录一下:
1报错如下:
events.js:167
throw er; // Unhandled 'error' event
^
Error: listen EADDRINUSE :::1221
at Server.setupListenHandle [as _listen2] (net.js:1286:14)
原因 端口冲突了
1杀掉node进程 2 修改端口号
参考 https://www.crifan.com/npm_run_dev_error_listen_eaddrinuse_127_0_0_1_8080/
2 警告如下 :
DeprecationWarning: current Server Discovery and Monitoring engine is deprecated, and will be removed in a future version. To use the new Server Discover and Monitoring engine, pass option { useUnifiedTopology: true } to the MongoClient constructor.
添加一句
mongoose.set('useCreateIndex', true)
网友评论