[英]Decode JSON object in req where content type 'application/x-www-form-urlencoded'
[英]Issue reading req.body content when sending application/x-www-form-urlencoded from postman — bodyparser already used
正如標題所說。 我正在從 postman 發送多部分表單數據,其中包含一些文本字段和圖像。 但是,當我 console.log(req.body) 我得到
{
'------WebKitFormBoundaryCpNHg1P01X54QAVr\r\nContent-Disposition: form-data; name': '"customerID"\r\n' +
'\r\n' +
'1\r\n' +
'------WebKitFormBoundaryCpNHg1P01X54QAVr\r\n' +
'Content-Disposition: form-data; name="make"\r\n' +
'\r\n' +
'honda\r\n' +
'------WebKitFormBoundaryCpNHg1P01X54QAVr\r\n' +
'Content-Disposition: form-data; name="model"\r\n' +
'\r\n' +
'accord\r\n' +
'------WebKitFormBoundaryCpNHg1P01X54QAVr\r\n' +
'Content-Disposition: form-data; name="year"\r\n' +
'\r\n' +
'2020\r\n' +
'------WebKitFormBoundaryCpNHg1P01X54QAVr\r\n' +
'Content-Disposition: form-data; name="color"\r\n' +
'\r\n' +
'white\r\n' +
'------WebKitFormBoundaryCpNHg1P01X54QAVr--\r\n'
}
如果我 console.log(req.body.keyName) 我總是有未定義的。 我已經實現了類似帖子的建議,即使用
app.use(bodyParser.urlencoded({
extended: true
}));
但它仍然不起作用。 我不確定我做錯了什么。 代碼片段如下。
服務器.js
const app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: true
}));
app.use(cors());
app.use('/users', userRouter);
app.use('/offers', offerRouter);
app.listen(PORT, (err)=>
{
if (err) console.log(err);
else console.log(`Server listening on port ${PORT}`);
});
路線
const multer = require('multer');
//required for mulitpart-formdata
const diskStorage = multer.diskStorage({
destination: "uploads/",
filename: (req, file, call_back) => {
//Prepend date to the filename or anything that makes
//the file unique so it won't be overwritten
call_back(null, Date.now() + "_" + file.originalname);
},
});
const upload = multer({ storage: diskStorage });
router.post("/request", upload.single("file"), (req, res, next) =>
{
GetBucket();
console.log(req.file);
})
要解析多部分請求,您需要 Multer 或 BusyBoy。 我建議 Multer ( https://www.npmjs.com/package/multer ) 因為它簡單易用,這里是一個使用 Multer 的例子
const Multer = require('multer');
// create multer instance
const multer = Multer({
storage: Multer.MemoryStorage, // we want to save parsed body in RAM
onError: function(err, next) {
console.log(err);
next(err);
}
});
function myController("/multipart/request", multer.single('name'), (req, res) => {
console.log(req.body.name);
});
注意:如果您與請求一起發送文件,請使用多部分請求,否則您可以使用application/x-www-form-urlencoded
或application/json
可以由正文解析器解析
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.