1辑奈、koa-bodyparser(參數(shù)解析)
npm install koa-bodyparser --save
const Koa = require('koa');
const app = new Koa();
const bodyparser = require('koa-body');
app.use(bodyparser());
2错森、koa-router (url)
?普通的路由
npm install koa-router --save
const Koa = require('koa');
const app = new Koa();
const koaRouter = require('koa-router');
const router = new koaRouter();
router.get("/", async (ctx, next) => {
????????????ctx.body = "get 請(qǐng)求";
})旧巾;
router.post("/", async (ctx, next) => {
????????????ctx.body = "post 請(qǐng)求"肯腕;
})蔬浙;
app.use(router.routes()).use(router.allowedMethods());
多級(jí)路由:
const Koa = require('koa');
const app = new Koa();
const koaRouter = require('koa-router');
let home = new koaRouter();
home.get("/", async (ctx, next) =>{
? ? ????ctx.body = "home get 請(qǐng)求"否纬;
})盖袭;
home.post("/", async (ctx, next) => {
? ? ? ? ctx.body = "home post 請(qǐng)求";
})熄诡;
let? article = new koaRouter();
article.get("/", async (ctx, next) => {
? ? ? ? ctx.body = "articel? get 請(qǐng)求";
});
article.post("/", async (ctx, next) => {
? ? ? ? ctx.body = "article post 請(qǐng)求";
})//總路由
let router = new? koaRouter();
router.use('/home',home.routes(),home.allowedMethods());
router.use('/article',article.routes(), article.allowedMethods());
app.use(router.routes()).use(router.allowedMethods());
3可很、koa-cors(跨域資源共享)
npm install koa2-cors --save
constcors =require('koa2-cors');
app.use(cors({ origin:function(ctx){
????????if(ctx.url ==='/test') {
????????????return"*";? ? // 允許來自所有域名請(qǐng)求
? ? ? ? }
????????return????'http://localhost:8080'; / 這樣就能只允許 http://localhost:8080 這個(gè)域名的請(qǐng)求了
????},
?????exposeHeaders: ['WWW-Authenticate','Server-Authorization'],
? ? ?maxAge:5,
?????credentials:true,
?????allowMethods: ['GET','POST','DELETE'],
?????allowHeaders: ['Content-Type','Authorization','Accept'],
}));
資源請(qǐng)求:
this.$axios.post('http://172.16.186.50:3000/', {參數(shù)}) .then((response) =>{
????????console.log(response)
?}) .catch(function(error){
????????console.log(error);
?});
4、koa-static (靜態(tài)資源服務(wù))
npm install koa-static? --save
const path = require('path')
const static = require('koa-static')
const app = new Koa()
//設(shè)置靜態(tài)資源的路徑
const staticPath = './demo'
app.use(static(
????path.join( __dirname,? staticPath)
))