Skip to content
章节导航

接口实现

说明

接口实现将用到如下技术:

  • node+express
  • postgres

1. 后端工程搭建

后端工程的搭建可参考SDK部署

2. 接口实现

2.1 添加数据库

  1. 首先,安装pg依赖
shell
npm i express pg –S
  1. 添加数据库配置 安装完依赖后修改工程结构目录如下:

/config/db.json为数据库配置文件,内容如下:

js
const config = {
    host: 'localhost',
    port: 5432,
    user: 'postgres',
    password: 'root',
    database: 'gis',
    // 扩展属性
    max: 40, // 连接池最大连接数
    idleTimeoutMillis: 3000, // 连接最大空闲时间 3s
};

module.exports = config;

2.2 接口实现

models为模型项,实现基于业务的封装实现,typhoon.js的内容如下:

js
const dbConfig = require('../config/db');
const pg = require('pg');
const pool = new pg.Pool(dbConfig);
const R = require('../R')

let typhoon = {
    // 获取台风列表
    getTyphoonList: function (req, res, next) {
        const { year } = req.query
        let SQL = `select * from typhoon_list where 1 = 1`;
        if(year) SQL += `and year = ${year}`
        pool.connect((isErr, client, done) => {
            client.query(
                SQL,
                function (isErr, result) {
                    done();
                    if (isErr) {
                        res.json(new R().err(isErr));
                    } else {
                        const data = result.rows
                        res.json(new R().ok(data));
                    }
                }
            );
        })
    },
};

module.exports = typhoon

routers为路由项,根据不同的业务逻辑拆分路由,typhoon.js的内容如下:

js
var express = require('express');
var router = express.Router();
var typhoon = require('../models/typhoon');

// 原生接口
router.get('/list', (req, res, next) => {
    typhoon.getTyphoonList(req, res, next)
});

module.exports = router;

app.js为启动入口,配置了开发调试的端口和路由的集成等,其内容如下:

js
const express = require('express');
const typhoonRouter = require('./routes/typhoon');
const app = express();

// 自定义跨域中间件
const allowCors = function (req, res, next) {
    res.header('Access-Control-Allow-Origin', req.headers.origin);
    res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS');
    res.header('Access-Control-Allow-Headers', 'Content-Type');
    res.header('Access-Control-Allow-Credentials', 'true');
    next();
};
app.use(allowCors);//使用跨域中间件

app.use('/typhoon', typhoonRouter);

app.listen(18888, () => {
    console.log('running at http://localhost:18888');
})

R.js为结果类,在结构提供试做统一格式的接口处理,其内容如下:

js
class R {
    constructor() {
        this.code = '200'
        this.msg = 'success'
        this.data = {}
        return this
    }

    ok(data) {
        this.code = 200
        this.msg = 'success'
        this.data = data
        return this
    }

    err(msg = '') {
        this.code = 500
        this.msg = msg || 'error'
        this.data = null
        return this
    }
}

module.exports = R

3. 启动

3.1 开发

shell
`node .\app.js`

3.2 部署

我们可以借助pm2进行服务的发布

shell
pm2 start .\app.js
示例: ❐ 查看