简体   繁体   English

Nodejs express 请求主体未定义

[英]Nodejs express Request body undefined

I am having trouble reading parameters from the request body for a post request i know this has been asked several times but all the answer are saying to call the body parser before calling app.use() for the routes i did this and also called bodyparser.urlencode() and and it's still giving me undefined whenever i console.log(req.body) or just prints {} ( an empty object)我无法从 post 请求的请求正文中读取参数我知道这已经被问过好几次了,但所有的答案都说在调用 app.use() 之前调用正文解析器我这样做了,也调用了 bodyparser .urlencode() 并且它仍然给我 undefined 每当我 console.log(req.body) 或只是打印 {} (一个空对象)

this is my code这是我的代码

const bodyParser=require('body-parser');
const express=require('express');
const app=express();
app.use(
   bodyParser.urlencoded({
     extended: false
   })
 )

 app.use(bodyParser.json())

 app.post('/endpoint', (req, res) => {
   console.log(req.body);
   res.status(400).send({ "ReturnMsg": "User Already Exits" });
 })

 // the port where the application run
const port = process.env.PORT || 6001;
app.listen(port, () => console.log(`Listening on port ${port}...`));

So form-data is NOT supported by body-parser , generally multipart/form-data (the mime type of form-data ) is used to upload files.所以form-data通过支持body-parser ,一般multipart/form-data (mime类型的form-data )被用于上载文件。 Most API related cases JSON or XML is used, and when you post a <form> from HTML it generally gets sent as application/x-www-form-urlencoded .大多数 API 相关案例都使用JSONXML ,当您从HTML发布<form> ,它通常会作为application/x-www-form-urlencoded

A one line excerpt from application/x-www-form-urlencoded or multipart/form-data?来自application/x-www-form-urlencoded 或 multipart/form-data 的一行摘录 :

Summary;概括; if you have binary (non-alphanumeric) data (or a significantly sized payload) to transmit, use multipart/form-data.如果您要传输二进制(非字母数字)数据(或非常大的有效负载),请使用 multipart/form-data。 Otherwise, use application/x-www-form-urlencoded.否则,使用 application/x-www-form-urlencoded。

Now, to POST from Postman,现在,从邮递员POST

Change the settings to either x-www-form-urlencoded or raw->then select JSON from the dropdown将设置更改为x-www-form-urlencodedraw->then select JSON from the dropdown

例子

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

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