简体   繁体   English

使用API​​密钥的ExpressJS API调用

[英]ExpressJS API Call with API Key

Trying to keep my code organized. 试图使我的代码井井有条。 I have a controller directory and router directory. 我有一个控制器目录和路由器目录。 The goal is to make an api call and retrieve data. 目标是进行api调用并检索数据。

CONTROLLER CONTROLLER

function searchName(req, res) {
res.setHeader("user-key", process.env.APIKEY)
res.redirect(`https://api-endpoint.igdb.com/games/?search=${req.params.game}&fields=*`)

 }

ROUTER 路由器

router.get('/search/:game', Controller.searchName)

I export router, and require it in my server.js file. 我导出路由器,并在我的server.js文件中要求它。 In POSTMAN, this works fine; 在POSTMAN中,这很好用; I do have my API Key hard coded in Postman. 我的API密钥确实用Postman硬编码。 I've tried many different methods but can't seem to pass the header with my ApiKey when making the initial request in the code. 我尝试了许多不同的方法,但是在代码中发出初始请求时似乎无法通过ApiKey传递标头。 Additionally, being new to nodejs, I'm not sure if the request redirect is sufficient in this scenario. 此外,由于是NodeJS的新手,所以我不确定在这种情况下请求重定向是否足够。 Ultimately, setHeader is not working 最终, setHeader无法正常工作

It sounds like you're trying to make an async call to another service, pull back some data, and send that back to the client that called your service. 听起来您正在尝试对另一个服务进行异步调用,拉回一些数据,然后将其发送回调用您服务的客户端。 In a nodejs application it's quite trivial to make a new HTTP request. 在nodejs应用程序中,发出新的HTTP请求非常简单。 Nodejs has a built in HTTP.Agent, but I'd suggest trying out the axios library as it makes it even easily. Node.js具有内置的HTTP.Agent,但是我建议尝试axios库,因为它使它变得更加容易。 This will result in something like this: 这将导致如下所示:

const axios = require('axios');

function searchGame(req, res) {
    const requestOptions = {
        method: 'GET',
        uri: `https://api-endpoint.igdb.com/games/?search=${req.params.game}&fields=*`,
        headers: {
            "user-key": process.env.API_KEY
        }
    }

    axios.get(requestOptions)
    .then(function (response) {
        // This is the data the remote service gave back
        res.send(response.data);
    })
    .catch(function (error) {
        // The remote gave an error, lets just forward that for now
        res.send({error: error});
    });
}

Here we build an axios request from the req object, we make the request using axios.get, we then wait for the "promise" (this is an async javascript concept if you've not come across it before), then we take the response from that and forward it back as the res . 在这里,我们从req对象构建一个axios请求,我们使用axios.get发出请求,然后等待“承诺”(如果您之前没有遇到过,这是一个异步javascript概念),然后我们将对此做出回应,并将其作为res转发回去。 Lets pretend for argument sake that this is a JSON response, but it could be anything. 让我们假装这是一个JSON响应,但这可以是任何东西。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM