我正在撰寫一個簡單的 REST 服務器作為 javascript 教程的一部分,但我不知道如何讀取 POST 資料,我什至不知道如何獲取 POST 資料的長度。(我在處理 GET 命令時沒有問題。)這就是我正在做的事情:
const http = require('http');
const URL = require('url').URL;
const book = {title:"Dune", author:"Frank Herbert"}
const app = http.createServer((req, res) => {
console.log("Headers:", req.headers);
accept = req.headers.accept;
console.log("Accept:", accept);
// contentLength = req.headers.contentLength;
// console.log("content length:", contentLength);
data = req.read(61);
console.log("req.read(61):", data);
let path=req.url;
if (req.method === 'GET') {
doGet(req, res, path);
} else if (req.method === 'POST') {
doPost(req, res, path);
}
})
function doGet(req, res, path) {
if (path === "/basic") {
console.log("Basic path")
res.writeHead(200, {"Content-Type": "text/json","Access-Control-Allow-Origin":"*"});
res.write(JSON.stringify(book));
res.end();
} else {
console.log("error path");
res.writeHead(404, {"Content-Type": "text/json","Access-Control-Allow-Origin":"*"});
// res.write(asHtml("Not Found"));
res.write(JSON.stringify("{Not Found: " path "}"));
res.end();
}
}
// to test this method, I use this curl call:
// curl --data "{title:'Stranger In a Strange Land',author:'Robert Heinlein'}" localhost:4000/add
function doPost(req, res, path) {
if (path === "/add") {
res.writeHead(200);
var data = '';
req.on("data", function(chunk) {
data = chunk;
})
console.log("req.on():", data);
var postData = req.body;
console.log("req.body:", postData);
var readData = req.read();
console.log("POST data by read:", readData);
res.end();
} else {
res.writeHead(400);
res.write('');
res.end();
}
}
app.listen(4000);
所以我可以accept用這個運算式得到頭的值:req.headers.accept
但是如果我說它req.headers.content-length會拋出一個錯誤,如果我說它req.headers.'content-length'甚至不會編譯。
如何讀取內容長度的值,以及如何讀取 POST 資料?
附錄:
我應該更清楚我的結果。的值req.body未定義。
這是上面代碼的輸出:(為了清楚起見,我對其進行了一些修改。)
Headers: {
host: 'localhost:4000',
'user-agent': 'curl/7.79.1',
accept: '*/*',
'content-length': '61',
'content-type': 'application/x-www-form-urlencoded'
}
Accept: */*
req.read(61): null
req.on():
req.body: undefined
POST data by read: null
如您所見,內容長度為 61 是正確的。但是req.body,我希望找到資料的地方是未定義的。
uj5u.com熱心網友回復:
帖子資料應該在,req.body但先嘗試決議正文。嘗試body-parser在您的應用上使用中間件,然后req.body再次檢查
這是此中間件的檔案以及如何讓您的應用程式自動為您解碼請求正文,尤其是在您使用 express 時,這就是您應該如何實作節點服務器的方式。第二個鏈接還介紹了如何設定一個簡單的 JavaScript 服務器,不需要body parser或express不想使用它,它直接來自 node.js 檔案。它確實需要更多設定,這就是express推薦的原因,但這取決于您。讓我知道這是否有幫助!
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/463008.html
標籤:javascript 节点.js
上一篇:行為型:八. 中介者模式
下一篇:Vue3:樹形選單顯示
