2

I have a front end application, which I would like to return results with from an Express backend. Let's just call those results country and city for this reference.

I have done a bunch of searching, but I cannot find any solid resources on the relationship between the front end and middleware. Yes, I know what these things are, and the order in which they should flow, but the confusion sits with :

  1. Do I need to connect my front end and middleware? How so?
  2. If I am already connected to my backend from the front end, would I also have to connect to middleware?
  3. How would I return the country and city from the middleware and/or express backend?

Any other info you think would be helpful for the greater dev community who is still learning would be beneficial.

Max.California
  • 207
  • 1
  • 2
  • 7
  • Middleware in the Express usage of the term (functions that get called during a request to do things to the request or response), or in the generic sense (like buses or database access layers)? – Zac Anger Jan 15 '21 at 01:43

2 Answers2

1

While you could return data from a middleware, it's probably not what you are trying to do. A middleware is a piece of code that is executed between the time the request is receive by your backend, and the resource is fetch. In a middleware you could do things such as check if a user has access to a certain resource or authenticate a user by some sort of credential passed with the request.

Either way, the way you would, typically, do request from your front-end to your backend is via an XmlHttpRequest. Those request are usually Asynchronous, so they usage will not block the whole page while being executed. There are many ways you could create XmlHttpRequest. The native Javascript way is kinda ugly so I would suggest using the fetch api instead. You could also go with third party library if you need to do more complex stuff. I personnally like axios but this is up to you.

To give you a better understanding of what Express is doing, it's basically an infinite loop that waits for http request. You need to defined routes, that execute function that returns data.

Here is a basic example. Note that this script is executed via NodeJS :

// myserver.js
const express = require('express')
const app = express()

app.get('/cities', (req, res) => {
  const cities = /** somehow get all the cities **/

  res.json(cities);
})

/** the rest of the server... **/
/** For example, the route for Countries **/

In the previous example, we've built a basic server that listen to the url localhost:3000/cities and execute a function when this url is fetched. The said function will fetch all the cities and return them as JSON.

In your frontend, You would need to do a XmlHttpRequest that would call this url, to get the server to execute the function, which will return the data. Phew... I hope I did not lost you there.

A typical example would be a simple call using the fetch api. Please note that this script is executed in the browser.

// myclient.js

async fetchAllCities() {
    const cities = await fetch('http://localhost:3000/cities');
    console.log(cities);
}

// just for fun, we add a click listener on a button and call the function defined above.
document.getElementById('myButton').addEventListener('click', async function() {
    // we fetch the cities when we click on the button ! 
    await fetchAllCities();
});

In the previous example, I am using the fetch function to call the url we declared in our Express server.

I'm also using Async / Await, which can be a little tricky, but it just mean Wait for the data to be there before going forward.

I highly suggest reading on the subject. Here are some references.

How do I return the response from an asynchronous call?

Understanding async/await on NodeJS.

Await from MDN

I hope this brief overview of XmlHttpRequest helped you get the base of how an API works.

Nicolas
  • 8,077
  • 4
  • 21
  • 51
0

Middleware is used to help the back-end do its job in processing incoming requests. It does not exist separate from the back-end. It's part of the back-end. For example, you might have middleware that checks to see if an incoming request is properly authorized/authenticated before the route can be handled by it's regular route handler.

Do I need to connect my front end and middleware? How so?

No. Your front-end sends requests to the back-end. The back-end may or may not use middleware to service the request. That's entirely up to the implementation in the back-end and what it needs to do for any given request.

If I am already connected to my backend from the front end, would I also have to connect to middleware?

No. You don't separately connect to middleware. You connect to your back-end and the back-end may or may not use middleware to do its job (something the front-end will have no knowledge of).

How would I return the country and city from the middleware and/or express backend?

You would have to show more details about what you're actually trying to return back from a request, but a common data format is JSON so you could construct a Javascript object with your desired response and then send it back to the client as the response from the incoming request using either res.json(someObj) or res.send(someObj) (both do the same thing if someObj is a Javascript object).

For example:

app.get("/getsomething", (req res) => {
    // do some processing here to get cityResult and countryResult
    // construct object to send back to client
    const obj = { city: cityResult, country: countryResult};

    // send this object as JSON back the the client as the response to this
    //   incoming request
    res.json(obj);
});
jfriend00
  • 683,504
  • 96
  • 985
  • 979
  • @Max.California - Did this answer your question? We posted a couple answers to your question and never heard any feedback or questions from you. Did you even see the answers? – jfriend00 Mar 03 '21 at 04:05