[英]Node JS Express how can I send a 404 error if a bad request is made to third party API?
In my Node JS server I have this route handler that sends a request to a third party API to get a username:在我的 Node JS 服务器中,我有一个路由处理程序,它向第三方 API 发送请求以获取用户名:
app.get('/players/:player', apiLimiter, function(request, response) {
const player = request.params.player;
const api_url = `https://api.com/shards/steam/players?filter[playerNames]=${player}`;
var options = {
method: "GET",
observe: 'body',
};
let apiRequest = https.request(api_url, options, function (res) {
let data = "";
res.on("data", chunk => {
data += chunk;
})
res.on("end", () => {
let objectParsed = JSON.parse(JSON.stringify(data));
response.send(objectParsed);
})
if(!player) {
res.status(404).send("Not found.");
}
})
apiRequest.end();
})
This works fine to get a user that exists.这可以很好地获取存在的用户。 However, if I put in a fake username to my /players page, that page still loads with a 200 status instead of getting a 404 response.
但是,如果我在 /players 页面中输入了一个假用户名,该页面仍会以 200 状态加载,而不是获得 404 响应。 The page loads and looks broken because it's not actually getting any data from the API.
页面加载并看起来已损坏,因为它实际上并未从 API 获取任何数据。
I feel like this is a dumb question .. In my research I have found how to handle errors if it's just the route, and not if it's the route dependent on the path parameter as in /players/:player我觉得这是一个愚蠢的问题 .. 在我的研究中,我发现如何处理错误,如果它只是路线,而不是如果它是依赖路径参数的路线,如 /players/:player
I found a question that was similar to mine ( How to throw a 404 error in express.js? ) and I tried using an If statement: if (!player){res.status(404).send("Not found."); }
我发现了一个与我类似的问题( 如何在 express.js 中抛出 404 错误? )并尝试使用 If 语句:
if (!player){res.status(404).send("Not found."); }
if (!player){res.status(404).send("Not found."); }
but no dice. if (!player){res.status(404).send("Not found."); }
但没有骰子。 Am I using this if statement in the wrong place?我是否在错误的地方使用了这个 if 语句?
How can I get my Node JS server to respond with a 404 if the user from the database doesn't exist?如果数据库中的用户不存在,如何让我的 Node JS 服务器以 404 响应?
You have to check the result of the API call and see if you got valid data back and send the 404 there.你必须检查 API 调用的结果,看看你是否得到了有效的数据并将 404 发送到那里。 I also added a check to make sure something was passed for the player name and send back a 400 (bad request) if there's no player specified at all:
我还添加了一个检查,以确保为玩家名称传递了一些信息,如果根本没有指定玩家,则发回 400(错误请求):
app.get('/players/:player', apiLimiter, function(request, response) {
const player = request.params.player;
if (!player) {
res.status(400).send("No player specified.");
return;
}
const api_url = `https://api.com/shards/steam/players?filter[playerNames]=${player}`;
var options = {
method: "GET",
observe: 'body',
};
let apiRequest = https.request(api_url, options, function(res) {
let data = "";
res.on("data", chunk => {
data += chunk;
})
res.on("end", () => {
let objectParsed = JSON.parse(data);
// test objectParsed here
if (!some condition in objectParsed) {
res.status(404).send("No data for that player name.");
} else {
response.send(objectParsed);
}
});
});
apiRequest.end();
});
Also, you don't want JSON.parse(JSON.stringify(data))
here.此外,您不想要
JSON.parse(JSON.stringify(data))
在这里。 Your data is already a string.您的数据已经是一个字符串。 Just do
JSON.parse(data)
.只需执行
JSON.parse(data)
。
FYI, if you use a small http request library such as got()
, this code gets a lot simpler as it accumulates the response and parses the JSON for you in one line of code as in:仅供参考,如果您使用小型 http 请求库,例如
got()
,则此代码会变得简单得多,因为它会在一行代码中累积响应并为您解析 JSON,如下所示:
let data = await got(options).json()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.