node.js使用express框架实现api接口开发(从零开始,超简单可直接复制)

目录

一、效果图

二、实现

1、引入express框架依赖

2、 新建启动文件(/server/index.js)

3、新建接口函数文件(/server/router.js)


一、效果图

二、实现

1、引入express框架依赖

在项目文件夹根目录下,打开控制台cmd,输入以下命令:

npm install express --save

(ps:如果下载太慢,可以去安装npm淘宝镜像,使用cnpm下载) 

2、 新建启动文件(/server/index.js)

主要是接口的配置及实现

// 引入express服务依赖
const express = require('express')
const app = express()

// express配置
app.use(express.json()) // 解析 JSON 格式的请求体数据(application/json)
app.use(express.urlencoded({extended: true})) // 解析 URL 编码格式的请求体数据(application/x-www-form-urlencoded)

// 添加接口目录文件【router.js】(接口函数所在目录)
const router = require('./router')
app.use('/', router)

// 设置接口监听
const port = 8888
app.listen(port, () => {
    console.log('服务已启动,端口号: ' + port)
})

3、新建接口函数文件(/server/router.js)

主要是接口执行的规则,这里的思路是先接口守卫(初步过滤),然后演示不同类型的接口执行情况

const express = require('express')
const router = express.Router()

/**
 * 接口过滤守卫(过滤黑白名单,已经权限验证等等)
 *  req 请求体
 *  res 返回体
 *  next 继续执行
 */
router.use(function (req, res, next) {

    console.log('请求头(包含cookies):')
    console.log(req.headers)

    // 接口守卫过滤
    if (true) {
        // 继续执行接口
        next()
    } else {
        // 结束接口,返回结果
        res.end(JSON.stringify({
            code: 500,
            msg: '非法操作!'
        }))
    }

})

/**
 * post接口
 */
router.post('/post_test', (req, res) => {

    console.log('请求体参数:')
    console.log(req.body)

    // 返回结果
    res.end(JSON.stringify({
        code: 200,
        msg: 'post请求成功!'
    }))

})

// get接口
router.get('/get_test', (req, res) => {

    console.log('请求体参数:')
    console.log(req.query)

    // 返回结果
    res.end(JSON.stringify({
        code: 200,
        msg: 'get请求成功!'
    }))

})

module.exports = router

  • 4
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值