![](/img/trans.png)
[英]node.js ~ express req.on('end') triggers but not req.on('data')
[英]Node.js Vanilla Routes Req.on not sending response
我正在構建一個普通的 Node.js 服務器來處理我的 React Native App 的后端。
我正在使用 Http.createServer 模塊,在其中我只是使用普通邏輯來確定請求的 URL,然后我有 postRoutes 類等來處理這樣的邏輯:
const server = http.createServer(async (req: any, res: any) => {
res.statusCode = 200;
res.setHeader('Content-Type', 'application/json');
const auth = new Authentication(req.headers["authorization"]);
if (req.method === "GET") {
} else if (req.method === "POST") {
if (req.url === "/test") {
auth.validateToken();
if (auth.getValidateMessage() === "Unauthorized") return res.end(auth.getValidateMessage());
return res.end("Hello")
}
// If no data is passed to the post route, then this will not run, and the request does not get a response
req.on('data', async (chunk: { toString: () => string | number; }) => {
if (req.url === "/register") {
const response: RouteResponseClass = await PostRoutes.register(chunk);
if (response.statusCode === 200) return res.end(JSON.stringify(response));
if (response.statusCode === 400) return res.end(JSON.stringify(response.data));
return res.end(response.message);
}
if (req.url === "/login") {
const response: RouteResponseClass = await PostRoutes.login(chunk);
if (response.statusCode === 200) return res.end(JSON.stringify(response));
if (response.statusCode === 400) return res.end(JSON.stringify(response.data));
return res.end(response.message);
}
});
// This will always hit first before req.on
}
// This will always hit first before req.on
return res.end("hey")
});
我的問題是這樣的:
正如我們所見,我正在使用req.on
函數,它在接收數據時調用回調。
這在通過這些路由接收數據時正常工作,例如在 /login 上。
但是:當用戶沒有發送任何數據(這不應該發生)時,請求不會結束,因為它沒有命中 req.on 回調函數,並且沒有任何東西可以處理它。
我嘗試過的:如果我在POST method
之外設置了res.end
,那么它會在請求到達req.on
之前結束請求,因為req.on
是異步的。
使用req.on
如何處理沒有數據發送到 post 路由?
謝謝大家的時間!
您需要稍微更改帖子處理程序內部的邏輯。 在.on("data")
回調中,只需收集請求中發送的所有塊並添加一個.on("end")
偵聽器,以便在請求正文中的所有數據都已被消耗時收到通知(這將如果請求正文為空,則立即觸發)。 在該回調中,您可以處理發送響應。 像這樣的東西:
// ...
} else if (req.method === "POST") {
// ...
let bodyBuffer = [];
req.on('data', chunk => {
bodyBuffer.push(chunk);
});
req.on('end', () => {
// convert the gathered chunks to string
const body = bodyBuffer.toString("utf8");
if (req.url === "/register") {
const response: RouteResponseClass = await PostRoutes.register(body);
if (response.statusCode === 200)
return res.end(JSON.stringify(response));
if (response.statusCode === 400)
return res.end(JSON.stringify(response.data));
return res.end(response.message);
}
if (req.url === "/login") {
const response: RouteResponseClass = await PostRoutes.login(body);
if (response.statusCode === 200)
return res.end(JSON.stringify(response));
if (response.statusCode === 400)
return res.end(JSON.stringify(response.data));
return res.end(response.message);
}
});
如果你使用像express這樣的框架來做這件事,你也可以省去很多痛苦。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.