基于node使用express搭建web服务器

237 阅读3分钟

安装express

Express 是一个保持最小规模的灵活的 Node.js Web 应用程序开发框架,许多流行的开发框架都基于 Express 构建。

mkdir expressProject 
cd expressProject
npm init
npm install express --save
npx express-generator

确保自己已经安装了node.js,依次执行cmd命令,创建一个expressProject工作目录,创建依赖包信息,安装express。这样就创建了一个携带package.json的文件夹。通过应用生成器工具 express-generator 可以快速创建一个应用的骨架。

Snipaste_2024-11-19_18-14-14.png 执行以下命令安装依赖,运行项目,浏览器输入http://localhost:3000/返回Welcome to Express即成功运行。

npm install
npm run start

安装nodemon

Nodemon是一种工具,可在检测到目录中的文件更改时自动重启Node应用程序,从而帮助开发基于Node.js的应用程序。

npm install nodemon --save-dev

修改package.json文件,运行npm run dev重启项目。

"scripts": {
    "start": "node ./bin/www",
    "dev": "nodemon ./bin/www"
  },

基本路由

路由是指确定应用程序如何响应对特定端点的客户端请求,该端点是 URI(或路径)和特定的 HTTP 请求方法(GET、POST 等)。

// routes/index.js
var express = require('express');
var router = express.Router();
const data = [
  {
    id: 1,
    name: 'John Doe',
    email: 'NfW9w@example.com',
  },
  {
    id: 2,
    name: 'Jane Doe',
    email: 'NfW9w@example.com',
  },
  {
    id: 3,
    name: 'Jack Doe',
    email: 'NfW9w@example.com',
  },
];
/* GET home page. */
router.get('/', function (req, res, next) {
  res.json({
    status: 200,
    message: 'Hello World!',
    data: {},
  });
});

/* GET users listing. */
router.get('/usersList', function (req, res, next) {
  // 200 OK
  res.status(200).json({
    status: 200,
    message: 'get users success',
    data: data,
  });
});
/* ADD user. */
router.post('/user', function (req, res, next) {
  // 200 OK
  data.push({
    id: data.length + 1,
    name: req.body.name,
    email: req.body.email,
  });
  res.status(200).json({
    status: 200,
    message: 'add user success',
    data: data,
  });
});
/* DELETE user. */
router.delete('/user/:id', function (req, res, next) {
  // 200 OK
  const list = data.filter((item) => item.id != req.params.id);
  res.status(200).json({
    status: 200,
    message: 'delete user success',
    data: list,
  });
});

/* UPDATE user. */
router.put('/user/:id', function (req, res, next) {
  // 200 OK
  data.map((item) => {
    if (item.id == req.params.id) {
      item.name = req.body.name;
      item.email = req.body.email;
    }
  });
  res.status(200).json({
    status: 200,
    message: 'update user success',
    data: data,
  });
});

module.exports = router;

可以借助apifox来测试接口结果。

注意: apifox网页版需要下载扩展才可以用于接口调试。下载地址

连接数据库

npm install mysql
// 连接数据库
const mysql = require('mysql')

const db = mysql.createPool({
  host: 'localhost',
  user: 'root',
  password: 'root',
  database: 'test_1'
})

module.exports = db
// 使用
const db = require("../config/db");
// 请求用户列表userList
router.get("/userList", function (req: Request, res: Response, next: NextFunction) {
  db.query("select * from users", (err, result) => {
    if (err) throw err;
    res.json({
      code: 200,
      data: result
    });
  })
});

配置typeScript

// 安装依赖
npm install typescript @types/express @types/node ts-node -D
// 新建tsconfig.json文件,配置如下
{
  "compilerOptions": {
    "module": "commonjs",
    "esModuleInterop": true,
    "target": "es6",
    "rootDir": "./",
    "outDir": "./build",
    "strict": true
  }
}
// 将routes,views等目录放到src目录下
// 新建nodemon.json文件,配置如下
{
    "watch": ["src", "bin"],
    "ext": "ts,json",
    "ignore": ["dist"],
    "exec": "ts-node ./bin/www.ts"
}
// 修改package.json文件
{
    "scripts": {
        "dev": "nodemon"
    }
}
// 修改所有js文件为ts
// bin/www.ts 修改这两个函数类型
/**
 * Normalize a port into a number, string, or false.
 */

function normalizePort(val: string) {
  var port = parseInt(val, 10);

  if (isNaN(port)) {
    // named pipe
    return val;
  }

  if (port >= 0) {
    // port number
    return port;
  }

  return false;
}

/**
 * Event listener for HTTP server "error" event.
 */

function onError(error: NodeJS.ErrnoException) {
  if (error.syscall !== 'listen') {
    throw error;
  }

  var bind = typeof port === 'string'
    ? 'Pipe ' + port
    : 'Port ' + port;

  // handle specific listen errors with friendly messages
  switch (error.code) {
    case 'EACCES':
      console.error(bind + ' requires elevated privileges');
      process.exit(1);
      break;
    case 'EADDRINUSE':
      console.error(bind + ' is already in use');
      process.exit(1);
      break;
    default:
      throw error;
  }
}
// app.ts
import { Request, Response, NextFunction } from "express";
interface CustomError extends Error {
  status?: number;
}
// error handler
app.use(function (err: CustomError, req: Request, res: Response, next: NextFunction) {
  // set locals, only providing error in development
  res.status(err.status || 500).send({
    status: err.status,
    message: err.message
  });
});
// 数据库
npm i --save-dev @types/mysql

const db = require("../config/db");
// 请求用户列表userList
router.get("/userList", function (req: Request, res: Response, next: NextFunction) {
  db.query("select * from users", (err:MysqlError, result: FieldInfo[]) => {
    if (err) throw err;
    res.json({
      code: 200,
      data: result
    });
  })
});

到此应该就搭建了基础的web服务了,开始开启下一段的旅程了。 目录结构大概是这样的。

your-project/
├── bin/
│   └── www.ts
├── src/
│   ├── app.ts
│   ├── routes/
│   │   └── index.ts
├── package.json
├── nodemon.json
├── tsconfig.json
└── node_modules/