前端小酱Vue

Vue+Koa2+axios+mongodb搭建的小demo

2019-01-17  本文已影响164人  秋楪祈

起因

最近在学Vue,在B站上看了个教学视频,但是视频里请求的接口都是人家的内网接口,我们根本访问不了,出于无奈,只能自己搭一个后台服务器,写接口返回数据。

安装axios,调通前后端数据请求

cd vue-client
npm i axios

vue-client/src/main.js中引入axios,并配置为原型链属性

image.png

注意

vue-client/config/index.js里,要配置proxyTable,target要配置为后端的域名

image

下面是我服务端端口:


console.png
chrome.png

后端服务配置

1.连接mongodb数据库

新建文件夹及文件db/index.js,并填写如下代码

const mongoose = require('mongoose');
const db = mongoose.connect("mongodb://localhost:27017/test", { useNewUrlParser: true }, function (err) {
    if (err) {
        console.log(err);
    } else {
        console.log("Connection success !")
    }
})

const Schema = mongoose.Schema;
//汽车
let carSchema = new Schema({
    car_id: { type: String },
    car_name: { type: String },
    create_time: {
        type: String,
        default: Date.now
    }
})

exports.Car = mongoose.model('Car', carSchema);

2.写一个car的控制器(server/contorller/car.js)

const Car = require("../db").Car

module.exports = {
    async add(ctx, next) {
        let { name, uid } = ctx.request.body;
        console.log(ctx.request.body);
        console.log(name);
        console.log(uid)
        let car = new Car({ car_id: uid, car_name: name })

        res = await car.save();
        if (res._id != null) {
            ctx.body = {
                code: 200,
                msg: "add success"
            }
        }
    },

    async find(ctx, next) {
        try {
            let carInfo = await Car.find({}, null)
            ctx.body = {
                code: 200,
                msg: "获取信息成功",
                list: carInfo
            }
        } catch (e) {
            console.log(e);
            ctx.body = {
                code: 500,
                msg: "获取信息,服务器异常,请稍后再试!"
            }
        }
    },

    async delcar(ctx, next) {
        let id = ctx.params.id;
        console.log(id)
        try {
            let res = await Car.findOneAndDelete({ car_id: id })
            if (res == null) {
                ctx.body = {
                    code: 500,
                    msg: "Delete fail"
                }
            } else {
                ctx.body = {
                    code: 200,
                    msg: "Delete Success"
                }
            }
        } catch (e) {
            console.log(e);
            ctx.body = {
                code: 500,
                msg: '删除失败,服务器异常!'
            }
        }
    }

}

3.配置后端路由(server/routers/index.js)

const router = require('koa-router')()
const controller = require('../controller')

router.get('/', async (ctx, next) => {
  await ctx.render('index', {
    title: 'Hello Koa 2!'
  })
})

router.get('/string', async (ctx, next) => {
  ctx.body = 'koa2 string'
})

router.get('/json', async (ctx, next) => {
  ctx.body = {
    title: 'koa2 json'
  }
})

router.get('/api/product', async (ctx, next) => {
  ctx.body = {
    title: 'product json'
  }
})
  .post("/api/addcar", controller.car.add)   // 添加汽车
  .get("/api/getinfo", controller.car.find)   // 查询汽车信息
  .get("/api/deletecar/:id", controller.car.delcar)  // 删除汽车信息 (有参数路由问题)
// .get("/api/deletecar", controller.car.delcar)  // 删除汽车信息 (有参数路由问题)

module.exports = router

接口示例

client

image.png

server

ruote.png image.png

浏览器展示

controller.png

其他的接口与上面示例一致,这有项目源码,欢迎大家下载指导

上一篇下一篇

猜你喜欢

热点阅读