代码承接简单服务器,修改 app.js
const koa = require('koa'),
app = new koa(),
Router = require('koa-router'),
router = new Router(),
host = '127.0.0.1',
port = 12899,
jsonwebtoken = require('jsonwebtoken'),
jwt = require('koa-jwt');
router
.post('/users/', (ctx, next) => {
ctx.body = 'add users';
})
.del('/users/:id', (ctx, next) => {
ctx.body = 'remove users';
})
.put('/users/:id', (ctx, next) => {
ctx.body = 'modify users';
})
.get('/users/:id', (ctx, next) => {
ctx.body = 'retrieve users';
});
app.use(router.routes());
app.listen(port, host, function () {
console.log(`server is running in http://${host}:${port}`);
});
使用一些其他性质,修改 app.js
const koa = require('koa'),
app = new koa(),
Router = require('koa-router'),
router = new Router({
prefix : '/user'
}),
host = '127.0.0.1',
port = 12899,
jsonwebtoken = require('jsonwebtoken'),
jwt = require('koa-jwt');
// 那个路由在前面就先匹配那个路由
router
.get('/:id/:level', async (ctx, next) => {
ctx.body = `get start: ${ctx.params.id}--${ctx.params.level}==>`;
await next(); //必须加这个才匹配 all
}, async (ctx, next) => {//中间件
ctx.body += ' second mid';
await next();
})
.all('/', (ctx, next) => {
ctx.body += ' all info';
// 设置跨域请求,跨域资源共享CORS(*指全部)
ctx.set('Access-Control-Allow-Origin', '*');
});
app.use(router.routes());
app.listen(port, host, function () {
console.log(`server is running in http://${host}:${port}`);
});