Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I properly set routes up for a Single Page App using Express.js?

I am attempting to build a single page app using Express.js. On my index.html page, I have a basic form, which upon submit will make a request to an API, retrieve the data, parse it, and then I want to render the parsed data as a list of links. Right now I am able to render the index page, and I can make the submission call to the API from the form that I added to the page. What I am confused about is how to properly redirect the data I get from the API call and then render it on the same page. I've built simple apps using Express before where there were multiple views, but never a single page app. For those apps, I know that for the response you could call something like res.render('name of view to render', data), but that is not working in this case. I've tried to find some solutions through this site and via the Express docs, but I have not seen anything that didn't also include using another framework like Angular. For the purposes of this app, I need to not include any additional frameworks, and I am a bit lost.

My function for calling the API looks like this right now. When it is called, I am directed to a page that just has the json displayed

app.use(express.static(path.join(__dirname, '/public')));
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());

app.use('/', express.static(path.join(__dirname, 'public')));

app.get('/search', function(req, res) {
  var title = req.query.movieTitle;
  var url = 'http://www.omdbapi.com/?s=' + title;

  request(url, function (err, response, body) {
    var results = JSON.parse(body);
    var movieTitles = results.Search;
    console.log(movieTitles);
    res.send(movieTitles);
  });
});
like image 592
Andy Pohl Avatar asked Aug 17 '16 06:08

Andy Pohl


1 Answers

The basic thing you have to do is:

  • define routes which your back-end app has to respond with the spa
  • send your "skeleton" file to the response on that routes

Example code:

const handler = (req, res) => res.send(path.join(__dirname, "path/to/your/index.html"))

const routes = ["/", "/hello", "/world"]

routes.forEach( route => app.get(route, handler) )

This should get you started

like image 102
Lazyexpert Avatar answered Oct 31 '22 00:10

Lazyexpert