使用 post 纯文本(Express.js 和 curl)的 Hello World

Hello World with post plain text (Express.js and curl)

我尝试从 POST 请求中检索纯文本数据,但得到 [object Object] 数据。我已经阅读了很多关于表达未定义问题的文章,但那总是 json,但我需要 plain/text 或只是字符串。好的 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
$ 

请求头内容类型错误,应该是:content-type: text/plain

对于 plain/text 请求,使用 bodyParser.text 代替 urlEncoded 很容易处理。 因为 urlEncoded 默认等待来自请求的 json 数据。 Documentation reference

这是带有文本解析器和正确内容类型的代码:

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