How to send backend data to the frontend?

Hi guys, I am pretty new to backend dev, and will certainly begin the backend course in due time. But I just have a very general question, which all I am looking for is a general point in the right direction. My question is pretty simple, but I am sure it’s complicated haha! The question is:

How do I send backend data to the front end using node/express?

For example, I have the following code which I am accessing the Yelp API. I can get a response as a console log, but then how do I send it to the front end? I am writing my web app in Vue js, and if you are interested the github repo is here.

Here is my code so far. I know it’s very basic, but again, I would just love a simple point in the right direction :slight_smile: Thank you in advance!!

var yelp = require('yelp-fusion'); 
// Yelp Fusion API
const token  = 'zb1p8LlaSDttz_8TXaEenGYv5UEF8Z6VoenBSzT873EIdec7hvcqvemcwkrTqtvYAqUyodgrviFIDcu7nZ8h3XOJ7OeopEgkdM8Nb-lgtIOEglYVucHb1GTmZWceWXYx';
const client = yelp.client(token);
client.search({
  term:'Coffee',
  location: 'Boulder'
})
.then(response => console.log(response.jsonBody.businesses))
.catch(e => console.log(e));

// send the yelp data to the client side using a dynamic search query from the input?
express.get('/search', function(req, res) {
  // how do I set this up?
});

/* Front end code
onSubmit () {
      if (this.searchTerm.length) {
        // reset loading signal
        this.loadingDone = false;
        this.items = [];
        // ajax get request with vue-resource
        this.$http.get(`/search/${this.searchTerm}`)
          .then(function(res) {
            this.results     = res.data;
            this.loadingDone = true;
          })
        ;
      }
*/

You are keeping your front end logic in a separate file, yes? So before you set up your routes, you need to invoke express in a variable called “app”, like so:

const app = express();

Now you can use “app.get()”, with the same arguments. Now to send your data to the front end, you need to paste the request to yelp into the callback of the .get function. Inside the .then function of your yelp request is where you take the json response, and send it to the client with:

 res.json(response.jsonBody.businesses)

I hope that helps.

Also, your ajax request on the front end might not work because your routes don’t match. To have it match, change the route inside your .get function with something like:

app.get("/search/:query", cb)

And use “req.params.query” to get the search query.

Cool thanks I will take a look now and post my results :slight_smile:And yes the front end logic is separate.

Jack

Ok, It’s not correct yet, but here is what I am trying to achieve,

Back end code

/** YELP API CODE
******************/
var yelp = require(‘yelp-fusion’);
// Yelp Fusion API
const token = ‘zb1p8LlaSDttz_8TXaEenGYv5UEF8Z6VoenBSzT873EIdec7hvcqvemcwkrTqtvYAqUyodgrviFIDcu7nZ8h3XOJ7OeopEgkdM8Nb-lgtIOEglYVucHb1GTmZWceWXYx’;
const client = yelp.client(token);

// send the yelp data to the client side using a dynamic search query from the input?
app.get(’/search:query’, function(req, res) {
console.log(req.params.query);

client.search({
term: ‘coffee’,
location: queryString.stringify({ q: req.params.query});
})
.then(response => res.jsonBody.businesses)
.catch(e => console.log(e));
});
Front End Code
showCafes(city = this.city) {
this.modal_type = ‘restaurants’;
this.show_modal = true;

  city = city.replace(' ', '+');
  console.log(city);
  if (city.length) {
    // ajax get request with vue-resource
    this.$http.get(`/search/${city}`)
      .then((res) => {
        this.cafes = res.data;
        console.log(this.cafes);
      });
  }

}
CONSOLE ERRORS
Response {url: “/search/Los+Angeles”, ok: false, status: 404, statusText: “Not Found”, headers: Headers…}
GET http://localhost:8080/search/Los+Angeles 404 (Not Found)

It looks like there is a typo in your route on the backend. It should be “/search/:query”. Try fixing that and see if it works. Where is your error coming from?

The error is coming from the get request and from the backend, here is my code, I’m not sure what is wrong to be honest…

BACKEND

// send the yelp data to the client side using a dynamic search query from the input?
app.get('/search/:query', function(req, res) {
  console.log(req.params.query);
  let results = [];
  client.search({
    term: 'coffee',
    location: req.params.query 
  })
  .then(response => {
    results.push(response.jsonBody.businesses);
    return results;
  })
  .catch(e => console.log(e));
});

FRONT END

showCafes(city = this.city) {
         this.modal_type = 'restaurants';
         this.show_modal = true;
          console.log(city);
          if (city.length) {
            // ajax get request with vue-resource
            this.$http.get(`/search/${city}`)
              .then((res) => {
                this.cafes = res.data;
                console.log(res.data);
              });
          }

Heres a link to my github to get a better idea of what I am doing.

Jack

Hey hey.

I’m not sure what your results array looks like in the Express get route, but you’re not passing it down into Vue. Instead of return results try res.json(results) instead, maybe

You need to use res.json(); inside the .then function to send a response to your front end with the data. Also I don’t believe you need to push the yelp response into an array because the businesses property should already be an array.

1 Like

Thank you, that seemed to do the trick. Here is my code and now it works, I am getting the data I expected :slight_smile:
BACKEND
app.get(’/cafes/:query’, function(req, res) {
console.log("Searched City: ", req.params.query );

  client.search({
    term: 'coffee',
    location: querystring.stringify({ q: req.params.query })
  })
  .then(response => {
     res.send(response);
  })
  .catch(e => console.log(e));
});

FRONT END

          if (city.length) {
            // ajax get request with vue-resource
            axios.get('/cafes/${city}').then(res => {
              this.cafes = res.data.jsonBody.businesses;
              console.log("cafe data: ", this.cafes);
            }).catch(e => {
              console.log(e, "error");
            });
          }
    }```

No problem!! Glad you got it to work.

I just saw this post and thought I would add, you never want to push your API keys up to gitHub. Even on a forum like this, I wouldn’t display the key publicly.

What should I do when pushing my code github? How do I hide my Keys and other important/sensitive data?

You can hide your keys in a .env file. The format is like
UPPERCASE_NAME=key
Make sure you have the dotenv module so you can access this key via process.env.keyname.
To keep this file hidden from github, make a .gitignore file if you don’t already have one, and add the path name of the .env file to it.
If you are pushing to heroku, chances are it might throw an error because heroku reads from github. If you ever encounter this error, there is an option in heroku to directly add the environment variables.

1 Like

This definitely correct for server-side code, however I think using the ‘dotenv’ module on client side can be a bit tricky. At least, it has been for me. Is there a simple way to use ‘dotenv’ on the client-side that I am missing? (using React)

Ohh was he referring to the client side? Usually what I do if I have to make a client side request is to use the componentDidMount event and fetch the keys from the server then store it in the state. Or without storing it, make a function where you fetch the keys from the server, and in the promise resolution you make your request.

As @codefu-chivy said, if you’re pushing server side code, environment variables are your friend.

I usually have a config setup that checks in I’m in “production” mode or not (I use Heroku for most things) and if not, loads in a variable file (example). If there’s anything that needs to be hidden, I immediately add that file to my .gitignore file so it doesn’t get added to the repo. Has the added benefit of letting me set up different environment variables for test or development.

If you’re pushing to Github with the intent of using Github Pages, things get more complicated. I can’t think of a way to hide it once it’s in the repo. I like the idea of pulling the variables from server and storing them in state.

1 Like

Secrets like api keys should not be transmitted from server to client - client memory can be examined in a debugger and data can be saved for later analysis - use secrets just on the server and transfer results to client

1 Like