如何用koa写后端接口

这里有一个例子:

/*
koa写接口:
1.引入路由,引入axois以及必要的模块
2.编写路由前缀
3.编写指定路径下的路由代码
  一般参数有:data status
  a.根据后台或者数据库定义的数据结构,编写正常返回的情况ctx.body,结构体应该是xxx
  b.如果返回异常,怎么处理
 */
import router from 'koa-router'
import axios from './utils/axios'

let router = new Router({prefix: '/geo'})

router.get('/getPosition', async (ctx) => {
  let {
    status,
    data: {
      province,
      city
    }
  } = await axios.get(`http://cp-tools.cn/geo/getPosition`)
  if (status === 200) {
    ctx.body = {
      province,
      city
    }
  } else {
    ctx.body = {
      province: '',
      city: ''
    }
  }
})

你可能感兴趣的:(javascript)