express simple notes

Create simple apps

Create empty folder

npm init

install express

npm install express --save

Create app.js

var express = require('express');
var app = express();

app.get('/', function (req,res){
    res.send('Hello World!');
});

var server =app.listen(3000, function (){
    var host = server.address().address;
    var port = server.address().port;

    console.log('Example app listening at http://%s:%s',host, port);;
});

Excuting an order

node app.js

If the system port is occupied, you can use the following command to view the port process and then kill the process and execute the command again

lsof -i:3000

Use a template engine

input the command

npm install ejs --save

Use app.set to set the template directory and engine, the app.js code is as follows

var express = require('express');
var app = express();

app.set('views','./views')
app.set('view engine', 'ejs')

app.get('/', function (req,res){
    res.render('index');
});

var server =app.listen(3000, function (){
    var host = server.address().address;
    var port = server.address().port;
   
    console.log('Example app listening at http://%s:%s',host, port);
});

 

Create a folder views, create index.ejs in views, enter hello lilu in index.ejs

Restart the server (Ctrl+C to close) and enter the command

node app

 

Use static file serving

Add the following code to the app.js file

app.use(express.static('./public',{
    maxAge: '0', //no cache
    etag: true
}));

Restart the service, you can access the static files in the /public directory as the root directory

Use the github API

Install the github package

npm install github --save

 

Server running in background

Install pm2 on the server

npm install -g pm2

start process

pm2 start app.js -i 4 //启动4个app.js进程

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325146750&siteId=291194637