![](/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.