koa2 rest mysql_使用koa2的REST API。几个路由器的通用前缀

我有两个实体,用户和员工。所以我想在不同的端点上都使用CRUD,但是它们都会被安装在“api”下,所以我可以定义api_v1,api_v2等等。

终点会是这样的:

get api/users

put api/users/12

delete api/users/12

get api/employees

....我无法为我的两条路线获取“api”前缀。无法让它与koa-mount一起工作。

我的文件:

server.js

// Dependencies

import Koa from 'koa'

import mongoose from 'mongoose'

import logger from 'koa-logger'

// import parser from 'koa-bodyparser';

import convert from 'koa-convert'

import serve from 'koa-static'

import Router from 'koa-router'

import session from 'koa-generic-session'

import mount from 'koa-mount'

// A seperate file with my routes.

import routingUsers from './users'

import routingEmployees from './employees'

// config

const config = require("./config/config")

// connect to the database

mongoose.connect(config.mongo.url)

mongoose.connection.on('error', console.error)

// Creates the application.

const app = new Koa()

// how to use koa-mount to make this work? Arghhhhh!

// const api = new Koa();

// api.use(convert(mount ('/api', app)))

// trust proxy

app.proxy = true

// sessions

app.keys = ['your-session-secret']

// Applies all routes to the router.

const user = routingUsers(Router())

const employee = routingEmployees(Router())

app

.use(logger()) // log requests, should be at the beginning

.use(user.routes()) // asign routes

.use(employee.routes()) // asign routes

.use(user.allowedMethods())

.use(employee.allowedMethods())

.use(convert(session())) // session not needed for an API??????

.use(convert(serve(__dirname + '/public'))) // for static files like images

// Start the application.

app.listen(3000, () => console.log('server started 3000'))

export default appusers.js(employees.js是相同的)。

// Export a function that takes the router

export default router => {

// Set a prefix of our api, in this case locations

const api = 'users'

router.prefix(`/${api}`);

// GET to all locations.

router.get('/', (ctx, next) =>

ctx.body = 'hello users');

// ctx.body = await Location.find());

// POST a new location.

router.post('/', async (ctx, next) =>

ctx.body = await new Location(ctx.request.body).save());

// Routes to /locations/id.

router.get('/:id', async (ctx, next) =>

ctx.body = await Location.findById(ctx.params.id));

// PUT to a single location.

router.put('/:id', async (ctx, next) =>

ctx.body = await Location.findByIdAndUpdate(ctx.params.id, ctx.body));

// DELETE to a single location.

router.delete('/:id', async (ctx, next) =>

ctx.body = await Location.findByIdAndRemove(ctx.params.id));

return router;

}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值