Skip to content

Latest commit

 

History

History
58 lines (44 loc) · 2.34 KB

notes.md

File metadata and controls

58 lines (44 loc) · 2.34 KB

Notes

Setting up Node.js App with Express

  1. Install Node.js,Download for macOS
  2. Open the terminal and run `node -v to check that it's been installed
  3. install NPM run npm install npm@latest -g
  4. run npm -v to check that it's installed
  5. cd to sites directory - run mkdir <dirname>
  6. cd <dirname>
  7. run echo "# Intro" >> README.md
  8. to initialise the repository using git, run git init
  9. run git add README.md
  10. git commit -m"initial commit"
  11. run git remote add origin [email protected]:Marie-L/<repo_name>.git
  12. then git push -u origin master
  13. to initialise the repository using NPM run, npm init to create the package.json file
  14. complete the following fields in the npm interactive editor : name, version, description, entry point (app.js), git repository (autofill), author
  15. to install run, npm install express --save
  16. then touch app.js

setup Express server in app.js

  1. use express by adding nodes require statement const express = require('express'); (the module is called express and it's the param passed into the parameter function) (the variable express can be used to access the methods and properties of the express module)
  2. call express function and assign it to the app variable const app = express();
  3. set up the development server using the listen method and pass in port number as param app.listen(3000);
  4. start server run node app.js
  5. in browser, type localhost:3000 enter. if there's an error lIke Cannot GET / it's working but need to give express instructions on how to respond to requests - doesnt have any resources to return for this route

Setting up routes

  • to create a route for the root, use the GET method (used to handle GET requests to a certain URL) on the app object, first param is the location parameter, then as callback add require and request objects . the callback function runs when the client requests the route. The send method is called to send data to the client
app.get('/', (req, res)=> { 
     res.send('test');
});

app.listen(3000, () => {
console.log('The application is running on localhost:3000!');
});

  • to add route that serves HTML
app.get('/',(req,res) => {
res.sendFile('index.html', {root: __dirname})
});

  • to add static server for front end files
app.use('/static', express.static('public'));