express从入门到牛逼

1) 安装express

npm install -g express-generator

2) 新建nodeApp

express nodeApp

3) 安装依赖

cd nodeApp && npm install

4) 项目列表

package.json // 依赖 命令行
package-lock.json
app.js // 入口文件  
views 
routes
public // 静态文件
    css
    img
    js
node_modules // 依赖
bin // listen:3000
    www // npm start 启动时调用的JS脚本文件

5) 启动

SET DEBUG=nodeApp:* & npm start

6) 热更新
因为在使用的过程中 更改了routes 中 index.js中的内容 发现没有用 所以觉得可能需要热更新 便去查询了一下 整理了代码

var express = require('express');
var app = express();
var fs = require("fs"); 
var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
// 为了路由能够热更新
app.use('/', function(req,res,next){
  indexRouter(req,res,next)
});
// 热更新
function cleanCache ( modulePath ) {
  var module = require.cache[modulePath];
  if (!module) {
    return;
  }
  // remove refrece in module.parent
  if(module.parent){
    module.parent.children.splice(module.parent.children.indexOf(module), 1);
  }
  require.cache[modulePath] = null; // reset
}

var watchFile = function ( filepath ){
  var fullpath = require.resolve(filepath);
  fs.watch(fullpath,function( event,filename ){
    if (event === "change") {
      cleanCache(fullpath);
      try {
          var routes = require(filepath);
          console.log("reload module",filename);
      } catch (ex) {
          console.error('module update failed');
      }
    }
  })
}
// 需要进行热更新的文件
var WatchFileAll = ["./routes/index"];
for (var i=0;i<g_WatchFiles.length;i++) {
    watchFile(WatchFileAll [i]);
}

setInterval(function() {
    indexRouter = require('./routes/index');
}, 1000);

也可以通过安装nodemon来进行热更新

npm install nodemon -g
// 更改package.json:
"scripts": {
   "start": "set DEBUG=myapp & nodemon ./bin/www"
 }
 // 之后每次更新文件 服务器都会更新并重新启动

7) 测试路由
在app.js同级的位置新建一个JS文件 about.js
在routes的index.js文件下加入以下代码

router.get('/about', function(req, res, next) {
  res.send('hello node about');
});

访问http://localhost:3000/about 则可以看到 hello node about
8) 路由方法

// get post put delete all

// GET method route
app.get('/', function (req, res) {
  res.send('GET request to the homepage');
});

// POST method route
app.post('/', function (req, res) {
  res.send('POST request to the homepage');
});

10) 连接后台 连接mySQL 或者 mongDB

// 安装mySQL并连接数据库
npm install mysql -g
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值