Express

Preface nonsense

After two years of front-end work, I have finally moved to the full stack. A large number of apis on node’s official website are not friendly for beginners to learn. I plan to follow the B station video and start to contact Node from the Express framework, and then go deep into the official website to learn each API after I pass the initial stage and encounter scenarios

Fast overhand routing

  1. Prepare the environment Node NPM
// Check the current version after the installation. Node -v NPM -vCopy the code
  1. New Folderexpress-testTo install express
npm install express --save
Copy the code
  1. Create a new file server.js and start writing nodejs
// Reference the Express module
const express = require('express');

// Execute the express function to generate the application instance
const app = express();

// Define a route
app.get('/'.function(req, res){
  res.send({ page: 'home' })
})

app.get('/about'.function(req, res){
  res.send({ page: 'About Us' })
})

app.get('/products'.function(req, res){
  res.send([
    { id: 1.title: 'Product A' },
    { id: 2.title: 'Product B' },
    { id: 3.title: 'Product C'},])})// Listen to start the server
app.listen(3000.() = > {
  console.log('App listening on port 3000! ');
})
Copy the code
  1. node server.jsrun

File changes are not listened for and a re-run is required each time a file is modified

  1. Nodemon run

NPM I -g nodemon Install the Nodemon. Run the nodemon server.js command to save the file

Two, static file hosting

Images, CSS files and JavaScript files in the public directory can be accessed by the following code

app.use('/static', express.static('public'))
Copy the code

You can now access files in the public directory with the /static prefix

http://localhost:3000/static/images/kitten.jpg
http://localhost:3000/static/css/style.css
http://localhost:3000/static/js/app.js
http://localhost:3000/static/images/bg.png
http://localhost:3000/static/hello.html
Copy the code

CORS cross-domain request

Resolve cross-domain problems

  1. The installationcors
npm install cors --save
Copy the code
  1. usecors
const cors = require('cors');
app.use(cors());
Copy the code

Or directly

app.use(require('cors') ());Copy the code