简体   繁体   English

如果向第三方 API 发出错误请求,Node JS Express 如何发送 404 错误?

[英]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.

相关问题 每当在我的 Node.js API 中发出 GET 请求时,我如何发送随机集合? - How can i send a random collection whenever a GET request made in my Node.js API? 如何修复 404 错误 Node JS Express POST 请求 - How to fix 404 error Node JS Express POST Request Node.js +向第三方服务发送API请求 - Node.js + Sending API Request to Third Party Service 向第三方API Node.js发出多个请求后如何发送响应 - How to send a response after making multiple requests to a third party API Node.js 使用Node获取对第三方API的请求 - GET request to a third party API using Node "从 node express 应用程序向需要自己身份验证的第三方 api 发出请求的最佳方法是什么?" - What is the best way to make a request from a node express app to a third party api that requires its own authentication? 后端从第三方获取 pdf。 我如何通过 REST api 发送给我的客户? - Backend gets a pdf from a third-party. How can I send it via REST api to my client? 如何使用Node Js和Express通过GET请求显示对象数组对于简单的RESTful API应用 - How Can I display an Array of Objects with a GET request using Node Js and Express For a simple RESTful API app 没有从我的第三方得到响应 object API 呼叫快递路线 node.js - Not getting a response object from my third party API call express routes node.js Node Express app.js 为 GET 请求提供 404 错误 - Node Express app.js giving a 404 error for GET request
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM