DeltaP
DeltaP

Reputation: 29

Question about own REST API and Fetch with 3rd Party API

I'm working on a backend to create a node js server to grab information from the IGDB API and display specific information. I'm new to node js with express and javascript so maybe I am completely missing something but here it goes.

I want to start off with creating an endpoint to search games through the IGDB API

`app.get('/test', (req, res) => {
    res.header("Access-Control-Allow-Origin", "*");
    res.header(
        "Access-Control-Allow-Headers",
        "Origin, Content-Type, Accept"
    )
        fetch("https://api-v3.igdb.com/games", {
            headers: {
                "user-key": "MY_KEY",
                Accept: "application/json"
            },
            method:"POST",
            body:`fields name; search "halo"; where version_parent = null;`
        })
            .then((response) => {
                return response.json();
            })
            .then((response) => {
                res.send(response);
            })
            .catch((err)=>{
                console.log(err);
            })
});`

This does send me the raw JSON Data to the game in the search body(in this case halo). So I am able to use this Endpoint already but I have to hardcode the name in the Body parameter. Now I have a second Javascript file that's linked to a html file that contains this code:

    test.addEventListener('click',()=>{

    fetch("http://localhost:3000/test",{
    })
        .then((response)=>{
            return response.json();
        })
        .then((response)=>{

        })
  });

For test reasons I just have a button to get the JSON information from the Endpoint.

Here I just want to grab the endpoint and then use the response to show the data in my html file. As I mentioned before the actual getting the information part works fine but the Problem I have now reached is that I do not now how to feed a search variable to my /test Endpoint. I need to be able to search for a game that a user types through html, so my thought was that I somehow have to be able too pass a variable from my second Javascript file to the endpoint but I don't know how to do that, so I am looking for help here.

Upvotes: 0

Views: 333

Answers (1)

Fahim Farook
Fahim Farook

Reputation: 1483

You can add a query parameter in your express API. i.e.

app.get('/test', (req, res) => {
    ...
    let search = req.query.search;
    fetch("https://api-v3.igdb.com/games", {
       ...
       body: 'fields name; search "' + search + '"; where version_parent = null;'
     })
     ...
});

And then in your second JS script;

test.addEventListener('click',() => {
    let search = document.getElementById("search-term").value;
    fetch("http://localhost:3000/test?search=" + search, ...})
    ...
});

Provided that you have an input in your HTML file;

<input type="text" name="name" id="search-term" value="value" />

Upvotes: 1

Related Questions