Express的使用
1.安装express
npm i express-generator
express app -e
cd app
npm i
2.目录分析
node_modules:依赖的模块包
public:存放静态资源
routes:路由操作
views:存放ejs模板引擎
app.js:主文件
package.json:项目描述文件
node www运行
默认端口3000
3.创建监听端口
app.js
var http = require("http");
//server 要在app下
var server = http.createServer(app);
server.listen(5000, () => {
console.log("启动成功,端口号5000");
});
4.新建config文件夹
configdb.js
npm i mysql
var mysql = require("mysql");
var pool = mysql.createPool({
connectionLimit: 20,
host: "127.0.0.1",
user: "root",
password: "root",
database: "wit.mes",
port: 3306,
});
module.exports = pool;
5.routes文件夹
var express = require("express");
var router = express.Router();
var pool = require("../config/configdb");
//get
router.get("", (req, res, next) => {
pool.getConnection((err, conn) => {
if (err) {
console.log(err);
} else {
console.log(req.query);
var sql = ``;
conn.query(sql, (err, data) => {
if (err) {
console.log(err);
} else {
res.send({
code: "0000",
data,
});
conn.release();
}
});
}
});
});
//post
router.post("", (req, res, next) => {
pool.getConnection((err, conn) => {
if (err) {
console.log(err);
} else {
var sql = ``;
conn.query(sql, (err, data) => {
if (err) {
console.log(err);
} else {
console.log("ok");
res.send({
code: "0000",
data: "ok",
});
conn.release();
}
});
}
});
});
6.app.js中引入
var indexRouter = require('./routes/index');
...
//404上面use
app.use('/', indexRouter);
7.package.json
npm i nodemon
"scripts": {
"start": "node app.js",
"server": "nodemon server.js"
},
8.启动
npm run server