0

I'm trying to create a react app that calls an api in an express server and displays the data. There are buttons that a user could press that have a value which would get passed into the api and the proper results would be shown.

My problem is passing the button value from react to express. I have tried req.params.query but it returns undefined. Note that the button values come from a different component.

App.js

 class App extends Component {
  state = {
    data: {},
  };

  search = async (query) => { <-- query returns button value
    fetch('/api')
      .then((res) => res.json())
      .then((data) => console.log(data)); // console log for now
  };

  render() {
    const {data} = this.state;
    return (
      <div>
        <div className={styles.container}>
          <Tables data={data} />
        </div>
      </div>
    );
  }
}

server.js

const url = GET_CHANNEL_ID + 'hard coded result' + API_KEY; 

app.get('/api', async (req, res) => {
  console.log(req.params.query); <-- undefined
  request(url, (error, response, body) => { <-- this works fine
    if (!error && response.statusCode == 200) {
      var info = JSON.parse(body);
      res.send(info.items[0]);
      console.log(info); 
    }
  });
});
user
  • 1,022
  • 2
  • 8
  • 30

2 Answers2

1

Assuming you have a parsing middleware setup (since later Express version stripped out most middleware) then it should be under req.query and you need to pass as a parameter. So in the front end you'd have:

fetch(`/api?q=${query}`)

Then in your server have the middleware, e.g. body-parser

import bodyParser from 'body-parser';
...
app.use(bodyParser.json());

then for your route:

app.get('/api', async (req, res) => {
    console.log(req.query); // this should contain params object, with the query parameter under the 'q' property
    ...
});
Jayce444
  • 8,725
  • 3
  • 27
  • 43
  • I already have bodyParser installed and thank you I now get the query params. However is there an easy way to get rid of the q="" part and just be left with the value? Thanks – user Nov 26 '20 at 02:47
  • Well you have to pass the parameter in somehow. The fetch request needs to be given that value, otherwise how is it gonna know. You can check out some of the answers here for various approaches to adding parameters to the request, but they're all basically different ways of adding it to the URL string: https://stackoverflow.com/questions/35038857/setting-query-string-using-fetch-get-request – Jayce444 Nov 26 '20 at 02:52
  • Sorry I should have clarified more. I meant in express how I could get rid the the q="" in express before passing it into my api. – user Nov 26 '20 at 02:54
  • 1
    Do you mean before passing it into the `request(url, (error, ...` part inside your route? Since the value is dynamic you can't define that URL as a string, it'd need to be a function, something like `const url = (query) => GET_CHANNEL_ID + query + API_KEY;`. Then in your route you can do `request(url(req.query.q), (error, ...` – Jayce444 Nov 26 '20 at 03:02
  • 1
    Thank you! really appreciate your help :) – user Nov 26 '20 at 03:04
0

You need to add the query param to your URL in the fetch function:

search = async (query) => {
  // add query param to URL
  fetch(`/api?query=${query}`)
    .then((res) => res.json())
    .then((data) => console.log(data));
};

Then for the server you can access the req.query object to get all of the query parameters:

const url = GET_CHANNEL_ID + 'hard coded result' + API_KEY; 

app.get('/api', async (req, res) => {
  console.log(req.query); // { query: 'whatever you sent in fetch' }
  request(url, (error, response, body) => {
    if (!error && response.statusCode == 200) {
      var info = JSON.parse(body);
      res.send(info.items[0]);
      console.log(info); 
    }
  });
});
machinehead115
  • 1,647
  • 10
  • 20
  • req.params.query is still undefined in express. Edit - req.query gives me { query: 'Value' } how can I get rid of the query part? req.query.id returns undefined – user Nov 26 '20 at 02:34
  • Edited my answer to include the server part as well. – machinehead115 Nov 26 '20 at 02:54