簡體   English   中英

NodeJS 服務器 - 無法讀取 POST 請求正文

[英]NodeJS Server - Unable to read POST request body

我正在嘗試在 Nodejs HTTP 服務器上創建一個簡單的帳戶系統。

我的服務器端代碼:

var server=http.createServer(function(req,res){

  if(req.url.startsWith("/api/")){
    console.log(" - // - API CALL - // -")
    switch (req.url.substr(4)) {
      case '/createAccount':
        if(req.method=="POST"){
          const requestBody = [];
          req.on('data', (chunks)=>{
            requestBody.push(chunks);
            console.log(chunks)
          });
          req.on('end', ()=>{
            console.log(requestBody)
            const parsedData = JSON.stringify(Buffer.concat(requestBody));
            console.log(parsedData)
            res.writeHead(200,{"Content-Type":"application/json","Access-Control-Allow-Origin": "*"});
            res.end(JSON.stringify({'error':false}));
          });
        }else{
          res.writeHead(405,{"Content-Type":"application/json","Access-Control-Allow-Origin": "*"});
          res.end(JSON.stringify({'error':true,'statuscode':'405','errortext':'You need to send a POST request to /createAccount.'}));
        }
        break;
      default:
        res.writeHead(404,{"Content-Type":"application/json","Access-Control-Allow-Origin": "*"});
        res.end(JSON.stringify({'error':true,'statuscode':'404','errortext':'This is not a valid API address.'}));
    }
  }else{
    console.log(" - // - NORMAL WEB PAGE - // -")
    res.writeHead(200,{"Content-Type":"text/html","Access-Control-Allow-Origin": "*"});
    let accountstate="not logged in"
    page="<html><body>This is my homepage!<br>You are "+accountstate+".</body></html>";
    res.end(page);
  }

});
server.listen(7000);
console.log(`Listening at http://localhost:7000`);

我發送的請求:

fetch("http://localhost:7000/api/createAccount",{
    method:"POST",
    body:{
        AccountName:"test",
        Password:"THISSHOULDBEENCRYPTED"
    }
}).then(r=>r.json()).then(r=>console.log(r))

發送請求后的控制台輸出:

 - // - API CALL - // -
<Buffer 5b 6f 62 6a 65 63 74 20 4f 62 6a 65 63 74 5d>
[ <Buffer 5b 6f 62 6a 65 63 74 20 4f 62 6a 65 63 74 5d> ]
{"type":"Buffer","data":[91,111,98,106,101,99,116,32,79,98,106,101,99,116,93]}

有誰知道為什么這是輸出以及我如何讀取普通請求正文? (預期輸出:{AccountName:"test",Password:"THISSHOULDBEENCRYPTED"})

我在許多網站上尋找答案,但所有解決方案都因相同的錯誤而失敗。

提前致謝!

這是我的固定代碼:

var server=http.createServer(function(req,res){

  if(req.url.startsWith("/api/")){
    console.log(" - // - API CALL - // -")
    switch (req.url.substr(4)) {
      case '/createAccount':
        if(req.method=="POST"){
          req.setEncoding('utf8');
          const rb = [];
          req.on('data', (chunks)=>{
            rb.push(chunks);
          });
          req.on('end', ()=>{
            const body=JSON.parse(rb.join(""));
            console.log(body)
            res.writeHead(200,{"Content-Type":"application/json","Access-Control-Allow-Origin": "*"});
            res.end(JSON.stringify({'error':false,'recieved':body}));
          });
        }else{...}
        break;
      default:
        ...
    }
  }else{...}

});
server.listen(7000);
console.log(`Listening at http://localhost:7000`);

和固定請求:

fetch("http://localhost:7000/api/createAccount",{
    method:"POST",
    Headers:{'Content-Type': 'application/json'},
    body:JSON.stringify({
        AccountName:'test',
        Password:'THISSHOULDBEENCRYPTED'
    })
}).then(r=>r.json()).then(r=>console.log(r))

基本上,將編碼設置為 UTF8 並將正文作為字符串發送將解決此問題。

暫無
暫無

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

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