【问题标题】:Hello World with post plain text (Express.js and curl)带有纯文本的 Hello World(Express.js 和 curl)
【发布时间】:2024-04-15 08:30:02
【问题描述】:

我尝试从 POST 请求中检索纯文本数据,但得到 [object Object] 数据。我已经阅读了很多关于表达未定义问题的内容,但这始终是 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
$ 

【问题讨论】:

  • How do I ask a good question?:“写一个总结具体问题的标题”
  • 内容类型是text/plain 不是plain/text
  • 感谢这个建议。无论如何它没有帮助
  • 标题很好,因为你好世界是我试图得到的
  • “写一个总结具体问题的标题 - “要求”不是问题o.O

标签: javascript node.js express curl post


【解决方案1】:

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

使用 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

【讨论】:

    最近更新 更多