簡體   English   中英

從發布請求獲取json到nodejs服務器

[英]get json from a post request to a nodejs server

json在請求對象中的何處?

例如,我知道我可以使用body-parser來做到這一點

var express = require('express');
var app = express();
var bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());


app.post('/', function(req, res){
    console.log(req.body)
    res.json({ message: 'goodbye'})
})

並啟動我的服務器並點擊

curl -H "Cont/json" -X POST -d '{"username":"xyz"}' http://localhost:3000/

但是有沒有正文解析器包括的方法嗎? 我可以在請求中看到json嗎?

您可以通過以下node stream進行操作

app.post('/', function(req, res){
    var body = "";
    req.on("data", function (data) {
        body += data;
    });
    req.on("end", function() {
        console.log(JSON.parse(body));
        res.json({ message: 'goodbye'})
    });
})

是的,你可以

//pipe to any writable stream req.pipe(process.stdout); 確定是否需要-您可以使用類似的方法將其保存到字符串中

  var tmpstr = "";
  req.on("data", function (data) {
    tmpstr += data;
  });
  req.on("end", function() {
   //do stuff
   console.log("\ndata length is: %d", tmpstr.length);
  });

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM