title: Node Express API + Front-End
body: <p>I'm coding my first "solo" nodejs webapp. Its based on a previous app (that I coded by following some kind of tutorial/course) which was an Express REST API that allows you to add/remove/update/list a Todo list. I've also implemented user authentication using jwt/bcrypt. All this is stored in a MongoDB database.</p>
  
  <p>Also note that all the endpoints return JSON.</p>
  
  <p>I'm now trying to add a front-end to the app. The API endpoints are at <code>/api/endpoint1</code>, <code>/api/endpoint2</code>, etc., and the views are rendered on <code>/view1</code>, <code>/view2</code>, etc. I'm doing this on purpose so that I can get the responses in plain JSON from the API, or show it in a webpage rendered.</p>
  
  <p>I started by using jQuery's ajax to make the calls but I realized this was not the way I wanted to do this. I removed all the js scripts on my webpage and started working directly on the server, rendering the pages with the info fetched from the api.</p>
  
  <p>This is what I have now:</p>
  
  <p><strong>server.js (main file) [sample]</strong></p>
  
  <pre><code>// RENDER 'GET TODOs'
  app.get('/todos', authenticate, (req, res) =&gt; {
      let auth = req.cookies['x-auth'];
      request({
          url: 'http://localhost:3000/api/todos',
          headers: {
              'x-auth': auth
          }
      }, function (error, response, body) {
          if (error || response.statusCode !== 200) {
              return res.status(response.statusCode || 500).send('Error'); // TODO
          }
          let bodyJSON = JSON.parse(body);
          res.render('todos', {
              title: 'Todo App - Todos',
              todos: bodyJSON.todos
          });
      });
  });
  
  // API endpoint to 'GET TODOs' (JSON)
  app.get('/api/todos', authenticate, (req, res) =&gt; {
      Todo.find({
          _creator: req.user._id
      }).then((todos) =&gt; {
          res.send({todos});
      }, (err) =&gt; {
          res.status(400).send(err);
      });
  });
  </code></pre>
  
  <p>I don't know why, but all this looks weird to me. I'm wondering if this is how I'm supposed to do this. I mean, is this a good approach/practice on making a API+front-end node app ?</p>
  
  <p>Also, I'm using an auth middleware twice: in the views and in the API itself. I guess this is OK?</p>
  
  <p>It would probably be better to use React/Angular but this is such a small app and I just wanted to make a really simple front-end.</p>