0

I first created a react app that was making API calls on client side, which is a big no no since it exposes the API key. So I have to create a backend express server to make API calls. However on client side, my react app allows you to type in a random username(which changes the state) in order to make an API call and get that users information. Is there a way to transfer state/ props from client side to backend express to complete an API call?

Here is the Express Code:

const express = require('express');
const app = express();
const fetch = require('node-fetch');

app.get('/api/customers', (req, res) => {

    fetch('https://na1.api.riotgames.com/lol/summoner/v4/summoners/by-name/huhi?api_key=<MY_API_KEY>')
    .then(res => res.json())
    .then(result => res.json(result));
});

const port = 5000;

app.listen(port, () => console.log(`Server started on port ${port}`))

in this section

fetch('https://na1.api.riotgames.com/lol/summoner/v4/summoners/by-name/huhi?api_key=<MY_API_KEY>')

Is there a way to change the username after 'by-name/' to reginald, doublelift, faker, etc(stored in the client-side react state).

example

fetch('https://na1.api.riotgames.com/lol/summoner/v4/summoners/by-name/reginald?api_key=<MY_API_KEY>')

or

fetch('https://na1.api.riotgames.com/lol/summoner/v4/summoners/by-name/doublelift?api_key=<MY_API_KEY>')

or

fetch('https://na1.api.riotgames.com/lol/summoner/v4/summoners/by-name/faker?api_key=<MY_API_KEY>')
Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
jabinx92
  • 49
  • 7
  • 1
    Uhhh....I mean the question is basically "can I send values to a backend". So short answer is yes. If you wanna know how to send values to your API, you can check how to do so via fetch on others posts like this one: https://stackoverflow.com/questions/35038857/setting-query-string-using-fetch-get-request then you should be able to access them within your route code via `req.query` (it used to be `req.params` but I believe that's deprecated. anyways, Google it) – Jayce444 Sep 27 '20 at 02:55

2 Answers2

1

It depends on how you send the username to your API, and the body parsing middleware you set in your express application.

fetch(`uri/by-name/${req.params.username}`)
// OR
fetch(`uri/by-name/${req.query.username}`)
// OR
fetch(`uri/by-name/${req.body.username}`)
lastr2d2
  • 3,604
  • 2
  • 22
  • 37
1

One of the solutions -

  1. On Backend/Api endpoint -
    // ...    
    app.get("/api/customers/:userId", (req, res)=>{
           fetch(`https://na1.api.riotgames.com/lol/summoner/v4/summoners/by-name/${req.params.userId}?api_key=<MY_API_KEY>`)
        .then(res => res.json())
        .then(result => res.json(result));
    })
    //...
  1. On the client side - on-submit-username-through-input or on-username-state-change call the api point viz. -
fetch(`/api/customers/${this.state.username}`).then(users => this.setState(users))
H S
  • 735
  • 4
  • 12