简体   繁体   中英

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

I try to retrieve plain-text-data from POST request but get [object Object] data. I have read much about express undefined issue, but that was always json, but I need plain/text or just string. Ok json is also for delivering strings, but I wonder if we can use just without json, but plain text.

So I did like this:

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
$ 

edit I corrected the curl command for "text/plain" and it not worked

$ curl -X POST  -H 'content-type: text/plain'  --data  "Hello world!"    http://localhost:3000/login
welcome, [object Object]u@h ~/Dropbox/heroku/post-process
$ 

Request header has wrong content-type, it should be: content-type: text/plain

And it's easy to handle with bodyParser.text for plain/text request instead urlEncoded. Because urlEncoded waiting json data for request by default. Documentation reference

Here is your code with text parser and right content-type:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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