簡體   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