繁体   English   中英

带有纯文本的 Hello World(Express.js 和 curl)

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

我尝试从 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
$ 

编辑我更正了“文本/纯文本”的 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
$ 

请求 header 的 content-type 错误,应该是: 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

暂无
暂无

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

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