我嘗試從 POST 請求中檢索純文本資料,但獲取[object Object]資料。我已經閱讀了很多關于 express undefined 問題的文章,但這總是 json,但我需要純文本/文本或字串。好的 json 也用于傳遞字串,但我想知道我們是否可以在沒有 json 的情況下使用純文本。
所以我是這樣的:
import express from 'express';
import bodyParser from 'body-parser';
const app = express()
const urlencodedParser = bodyParser.urlencoded({ extended: false })
app.post('/login', urlencodedParser, function (req, res) {
console.log(req.body)
res.send('welcome, ' req.body)
})
app.listen(3000, () => {
console.log('Example app listening on port 3000!');
console.log('http://localhost:3000');
});
$ curl -X POST -H 'content-type: plain/text' --data "Hello world!" http://localhost:3000/login
welcome, [object Object]u@h ~/Dropbox/heroku/post-process
$
編輯 我更正了“text/plain”的 curl 命令,但它不起作用
$ curl -X POST -H 'content-type: text/plain' --data "Hello world!" http://localhost:3000/login
welcome, [object Object]u@h ~/Dropbox/heroku/post-process
$
uj5u.com熱心網友回復:
請求頭的內容型別錯誤,應該是: content-type: text/plain
使用 bodyParser.text 處理純文本/文本請求而不是 urlEncoded 很容易。因為 urlEncoded 默認等待來自請求的 json 資料。檔案參考
這是帶有文本決議器和正確內容型別的代碼:
import express from 'express';
import bodyParser from 'body-parser';
const app = express()
const textParser = bodyParser.text({
extended: false
})
app.post('/login', textParser, function (req, res) {
console.log(req.body)
res.send('welcome, ' req.body)
})
app.listen(3000, () => {
console.log('Example app listening on port 3000!');
console.log('http://localhost:3000');
});
$ curl -X POST -H 'content-type: text/plain' --data "Hello world!" http://localhost:3000/login
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/374085.html
標籤:javascript 节点.js 表达 卷曲 邮政
下一篇:我如何發送回應以做出反應?
