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
- Prepare the environment Node NPM
// Check the current version after the installation. Node -v NPM -vCopy the code
- New Folder
express-test
To install express
npm install express --save
Copy the code
- 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
node server.js
run
File changes are not listened for and a re-run is required each time a file is modified
- 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
- The installation
cors
npm install cors --save
Copy the code
- use
cors
const cors = require('cors');
app.use(cors());
Copy the code
Or directly
app.use(require('cors') ());Copy the code