Express JS

What is a server?

  • A server is a computer that runs a program.
  • server returns a response to a request.

Express - response methods

  • app.get takes in two arguments: path and callback function.
  • the call back function takes in two arguments: request and response.
  • response has many methods: send, json, status, etc.
    • response.send sends a string to the client.
    • response.json sends a json object to the client.
    • response.status sets the status code.
    • response.set sets the header.
    • response.type sets the content type.
    • response.redirect redirects the client to a new url.
    • response.render renders a template.

Heruko - deployment

  • Heruko is a tool that helps you deploy your app to Heroku.
  • set the port for heruko as const port = process.env.PORT || 3001.
  • push the app to Heruko. heroku create creates a new app.
  • heroku add adds a new dependency to the app.
  • git push heroku master pushes the app to Heruko.

Express get and post

  • app.get takes in two arguments: path and callback function
app.get('/', (req, res) => {
  res.send('Hello World');
});
  • app.post takes in two arguments: path and callback function
app.post('/', (req, res) => {
    req.send(`Hello ${req.body.name}`); // sends a string to the client. POST request body is a json object with data sent by the client.
});

BONUS - Environments

  • development - this is where you write your code, test your code, and run your code. its usually a local machine.
  • test - this is where you test your code that was written in development.
  • staging - this is a replica of your production environment, to test your code before you deploy it to production.
  • production - this is where your code is deployed and used by the world.

how does data get store in the sever

  • The developer team populates the server with the data manually, because they have access to the server code.

  • Users of the app populate the server with data by sending data from the client side of the application to the server.

  • User use POST requests to send data to the server.

middleware

  • middleware is a function that runs before the request is handled by the server.
  • res.body upon console login shows up empty because the middleware function has not run yet.
  • Just as we need to parse data from an API response on the client side, we also need to set up functionality on the server so it can receive data from the client.
  • When we tried our POST request before, it didn't work as intended because we never instructed the server how it should read and parse data to be used.

parsing incoming data

  • parse incoming string or array data
    app.use(express.urlencoded({ extended: true })); // here use is the middleware function, extend
    • extended: true option set inside the method call informs our server that there may be sub-array data nested in it as well, so it needs to look as deep into the POST data as possible to parse all of the data correctly.
  • parse incoming json data
    app.use(express.json());

send file and statics

  • if we would like to send file isnted of json res.sendFile('index.html')
  • app.use(static('public'));
  • Express.js middleware that instructs the server to make certain files readily available and to not gate it behind a server endpoint.

Add the following code to the top of the server.js file, near the two app.use() methods:

fetch and post req

  • fetch() functionality performs GET requests.
  • fetch also supports json
fetch('/api/animals', {
  method: 'POST',
  headers: {
    Accept: 'application/json',
    'Content-Type': 'application/json'
  },
  body: JSON.stringify(animalObject)
})
  .then(response => res.json())
  .then(postResponse => {
    console.log(postResponse);
    alert('Thank you for adding an animal!');
  });

all other routes (wildcard routes)

  • we can add a wild card route that directs use to a page if the routes dont match
app.get('*', (req, res) => {
  res.sendFile(path.join(__dirname, './public/index.html'));
});

.

  • The order of your routes matters! The * route should always come last. Otherwise, it will take precedence over named routes, and you won't see what you expect to see on routes like /zookeeper.

router

  • instead of passing around the same app to every file, we're going to use another feature of Express.js called the Router.
    const router = require('express').Router();
router.get('/', (req, res) => {
  res.sendFile(path.join(__dirname, '../../public/index.html'));
});
module.exports  = router; // and finally require and import router file 
//main js
const animalRoutes = require('../apiRoutes/animalRoutes');
router.use(animalRoutes);

module.exports = router;