express 创建项目

  • 创建项目根目录

  • 载入目录初始化项目npm init 此时生产pakage.json文件,该文件主要记载函数依赖及项目信息,初始化时会提示输入入口文件、版本信息、授权信息等一系列信息,具体如下

{
 "name": "app",
 "version": "1.0.0",
 "description": "",
 "main": "app.js",
 "scripts": {
   "test": "echo \"Error: no test specified\" && exit 1"
 },
 "author": "",
 "license": "ISC",
 "dependencies": {
   "express": "^4.15.3"
 }
} 
  • 安装express
    npm install --save express
    • --save参数为设置依赖(必须)
  • 创建项目入口文件app.js,项目名需与pakage,json中定义的main保持一致。
    • eg:
var express = require('express');
var app = express();

//设置接口若无环境变量影响则为3000
app.set('port', process.env.PORT || 3000);
// 定制 404 页面
app.use(function(req, res){
res.type('text/plain');
res.status(404);
res.send('404 - Not Found');
});
// 定制 500 页面
app.use(function(err, req, res, next){
console.error(err.stack);
res.type('text/plain');
res.status(500);
res.send('500 - Server Error');
});
app.listen(app.get('port'), function(){
console.log( 'Express started on http://localhost:' +
app.get('port') + '; press Ctrl-C to terminate.' );
});

你可能感兴趣的:(express 创建项目)