博客
关于我
nodejs中express的使用
阅读量:792 次
发布时间:2023-02-16

本文共 2070 字,大约阅读时间需要 6 分钟。

Express 开发框架入门

Express 是一个基于 Node.js 平台的快速、开放且极简的 Web 开发框架,广泛应用于构建高效的后端服务。其地址为 https://www.expressjs.com.cn/

Express 与 HTTP 对比

Express 是在 HTTP 模块的基础上封装实现的,两者的主要区别在于:

  • HTTP 是原生模块,直接操作
  • Express 提供了更高级的接口和功能,便于开发
快速上手 Express

使用 Express 搭建 Web 服务非常简单,步骤如下:

  • 安装模块:npm i express

  • 引入模块:let express = require('express');

  • 创建服务:let app = express();

  • 配置路由:app.get('/index',(req,res) => { res.send('内容'); });

  • 启动服务器:app.listen(3000, () => { console.log('服务器启动成功'); });

  • 路由配置

    路由是 Express 的核心功能,通常采用以下方式:

    • 定义请求方式和路径:app.method(path, callback)

    • 常用请求方式包括 GET、POST、PUT、DELETE 等

    示例代码:

    // 定义路由app.get('/add', (req, res) => { res.send('hello,我是添加get数据');});app.put('/add', (req, res) => { res.send('hello,我是添加put数据');});app.delete('/add', (req, res) => { res.send('hello,我是添加delete数据');});app.get('/goods', (req, res) => { const goods = [ { id: 1, goodsname: 'T恤', price: 25 }, { id: 2, goodsname: '卫衣', price: 30 } ]; res.send(goods);});
    模块化路由

    为了便于管理路由,建议使用模块化路由:

  • 创建单独的路由文件

  • 使用 express.Router() 创建路由模块

  • 将路由模块导出并在主应用中使用

  • 示例代码:

    // 路由文件:student.jsconst express = require('express');const stuRouter = express.Router();

    // 定义路由stuRouter.get('/stu/add', (req, res) => {res.send('添加学生信息');});stuRouter.get('/stu/update', (req, res) => {res.send('修改学生信息');});stuRouter.get('/stu/del', (req, res) => {res.send('删除学生信息');});stuRouter.get('/stu/show', (req, res) => {res.send('查询学生信息');});

    // 导出模块module.exports = stuRouter;

    // 使用路由模块app.use('/student', require('./student'));

    路由参数获取

    获取路由参数有三种方式:

    • GET 请求参数:通过 req.query 获取

    • POST 请求参数:通过 req.body 获取

    • 动态路由参数:通过 req.params 获取

    动态路由示例
    // 动态路由app.get('/article/:name/:id', (req, res) => { res.send(req.params);});
    数据库连接与登录功能

    在 Express 中实现登录功能通常需要连接数据库。以下是一个简单的实现示例:

    // 数据库连接配置const mongoose = require('mongoose');mongoose.connect('mongodb://localhost:27017/mydb', { useNewUrlParser: true, useUnifiedTopology: true });

    // 登录功能实现app.post('/login', (req, res) => {const user = new User(req.body);user.save((err, user) => {if (err) {return res.status(500).send('用户已存在');}return res.send({ success: true, user: user });});});

    注意事项:

    • 确保数据库连接配置正确
    • 引入相应的数据库驱动如 mongoose
    • 添加密码加密功能

    转载地址:http://xtjfk.baihongyu.com/

    你可能感兴趣的文章
    No 'Access-Control-Allow-Origin' header is present on the requested resource.
    查看>>
    NO 157 去掉禅道访问地址中的zentao
    查看>>
    no available service ‘default‘ found, please make sure registry config corre seata
    查看>>
    No compiler is provided in this environment. Perhaps you are running on a JRE rather than a JDK?
    查看>>
    no connection could be made because the target machine actively refused it.问题解决
    查看>>
    No Datastore Session bound to thread, and configuration does not allow creation of non-transactional
    查看>>
    No fallbackFactory instance of type class com.ruoyi---SpringCloud Alibaba_若依微服务框架改造---工作笔记005
    查看>>
    No Feign Client for loadBalancing defined. Did you forget to include spring-cloud-starter-loadbalanc
    查看>>
    No mapping found for HTTP request with URI [/...] in DispatcherServlet with name ...的解决方法
    查看>>
    No mapping found for HTTP request with URI [/logout.do] in DispatcherServlet with name 'springmvc'
    查看>>
    No module named 'crispy_forms'等使用pycharm开发
    查看>>
    No module named cv2
    查看>>
    No module named tensorboard.main在安装tensorboardX的时候遇到的问题
    查看>>
    No module named ‘MySQLdb‘错误解决No module named ‘MySQLdb‘错误解决
    查看>>
    No new migrations found. Your system is up-to-date.
    查看>>
    No qualifying bean of type XXX found for dependency XXX.
    查看>>
    No qualifying bean of type ‘com.netflix.discovery.AbstractDiscoveryClientOptionalArgs<?>‘ available
    查看>>
    No resource identifier found for attribute 'srcCompat' in package的解决办法
    查看>>
    no session found for current thread
    查看>>
    no such file or directory AndroidManifest.xml
    查看>>