04.axios与后台 (Vue全栈开发学习笔记)

2021-05-07  本文已影响0人  笑着字太黑
04.axios与后台.jpg

后台代码:

1. dao.js:封装mongodb基本的增删改查操作

const MongoClient = require('mongodb').MongoClient

class DAO{
    constructor(url, dbName, collectionName) {
        this.url = url;
        this.dbName = dbName;
        this.collectionName = collectionName
    }
    _connect() {
        return new Promise((resolve , reject) => {
            MongoClient.connect(this.url, {useUnifiedTopology: true }, (err,client) => {
                if (err) return rejects(err, client);
                resolve(client)
            })
        })
    }
    insert(obj, isMany) {
        return new Promise((resolve, reject) => {
            this._connect().then(client => {
                let db = client.db(this.dbName)
                if (isMany) {
                    db.collection(this.collectionName).insertMany(obj).then(res => {
                        resolve(res)
                        client.close()
                    })
                } else {
                    db.collection(this.collectionName).insertOne(obj).then(res => {
                        resolve(res)
                        client.close()
                    })
                }
            })
        })
    }

    delete(obj, isMany) {
        return new Promise((resolve, reject) => {
            this._connect().then(client => {
                let db = client.db(this.dbName)
                if (isMany) {
                    db.collection(this.collectionName).deleteMany(obj).then(res => {
                        resolve(res)
                        client.close()
                    })
                } else {
                    db.collection(this.collectionName).deleteOne(obj).then(res => {
                        resolve(res)
                        client.close()
                    })
                }
            })
        })
    }

    update(filter, updater) {
        return new Promise((resolve, reject) => {
            this._connect().then(client => {
                let updaterCpy = { $set: updater };
                let db = client.db(this.dbName)
                    db.collection(this.collectionName).updateMany(filter, updaterCpy).then(res => {
                        resolve(res)
                        client.close()
                    })
            })
        })
    }

    query(obj) {
        let arr = []
        obj = obj || {}
        return new Promise((resolve, reject) => {
            this._connect().then(client => {
                let db = client.db(this.dbName)
                    let queryRes = db.collection(this.collectionName).find(obj)
                    queryRes.each((err, data) => {
                        if(data != null) {
                            arr.push(data)
                        } else {
                            resolve(arr)
                        }
                    })
            })
        })
    }

    push(filter, updater, arrayFilters, upsert) {
      return new Promise((resolve, reject) => {
          this._connect().then(client => {
              let updaterCpy = { $push: updater };
              let db = client.db(this.dbName)
                  db.collection(this.collectionName).updateMany(filter, updaterCpy, arrayFilters, upsert).then(res => {
                      resolve(res)
                      client.close()
                  })
          })
      })
    }
}
module.exports = DAO

2. routes\index.js:后台提供api接口

var express = require('express');
var app = express();

const DAO = require('../dao')
const dao = new DAO('mongodb://localhost:27017/', 'test', 'action')

app.post('/update', (req, res) => {
    let filter = { name:req.body.filterName }
    let update = { name:req.body.name }
    dao.update(filter, update).then(result => {
        res.send('更新成功')
    })
}),

app.post('/push', (req, res) => {
  let filter = req.body.filter 
  let update = req.body.update 
  let arrayFilters = req.body.arrayFilters
  dao.push(filter,update,arrayFilters,{'upsert': true}).then(result => {
      res.send('更新成功')
  })
}),

app.post('/del', (req, res) => {
    let obj = { ymd:req.body.ymd }
    dao.delete(obj).then(result => {
        res.send('删除成功')
    })
})

app.post('/add', (req, res) => {
  let obj = req.body.addObj
  dao.insert(obj).then(result => {
      res.send('插入成功')
  })
})

app.get('/init', (req, res) => {
  let queryCondition = {}
  if(req.query.ymd) {
    queryCondition['ymd'] = req.query.ymd
  }
  if(req.query.director) {
    queryCondition['userRecords.director'] = req.query.director
  }
  dao.query(queryCondition).then(result => {
    res.send({ result })
  })
})

app.get('/select', (req, res) => {
  let queryCondition = {}
  if(req.query.filter) {
    queryCondition = req.query.filter
  }
  dao.query(queryCondition).then(result => {
    res.send({ result })
  })
})

module.exports = app;

3.app.js:配置路由路径

var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');

// http://localhost:3000/web
app.use('/web', indexRouter);
// http://localhost:3000/users'
app.use('/users', usersRouter);

前台代码:

1. src\network\lanzyrequest.js:封装axios操作

import axios from 'axios'

const axiosInstance = axios.create({
    baseUrl: 'api', 
    timeout: 5000
})

export function lanzyRequest(config) {
    return axiosInstance(config)
}
这里baseUrl: 'api' 的设定
通过config/index.js的跨域设定,
实际指向地址为 http://localhost:3000/web
  1. src\main.js:
import lanzyRequest from ./network/lanzyrequest.js
Vue.prototype.lanzyRequest = lanzyRequest

3.src\App.vue: 参考使用方法

    this.$lanzyRequest.request({
        method: 'get',
            url: '/init',
            params: {key: value}
    }).then((res) => {
    }).catch((err) => {
    })
    this.$lanzyRequest.request({
        method: 'post',
        url: '/add',
        data: {
            addObj: {key: value}
        }
    }).then((res) => {
    }).catch((err) => {
    })
    // 同步调用
    async xxxxOnclick (e) {
        await this.$lanzyRequest.request(xxxx)
    } 
4.config\index.js:axios跨域设定
    proxyTable: {
      '/api': {
        // 前端调用/api时request发送至后台目标接口域名http://localhost:3000/web
        target: 'http://localhost:3000/web', 
        secure: false,
        changeOrigin: true, // 是否跨域
        pathRewrite: {
          '^/api': '' // 重写接口
        }
      },
      cssSourceMap: false
    },
上一篇下一篇

猜你喜欢

热点阅读