node

node常用的npm包及使用方法(koa2)

2018-11-20  本文已影响0人  ysp123

1、koa-bodyparser(参数解析)

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 请求";
});
router.post("/", async (ctx, next) => {
            ctx.body = "post 请求";
});
app.use(router.routes()).use(router.allowedMethods());

多级路由:

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 请求";
});
home.post("/", async (ctx, next) => {
        ctx.body = "home post 请求";
});
let  article = new koaRouter();
article.get("/", async (ctx, next) => {
        ctx.body = "articel  get 请求";
});
article.post("/", async (ctx, next) => {
        ctx.body = "article post 请求";
})

//总路由
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"*";    // 允许来自所有域名请求
        }
        return    'http://localhost:8080'; / 这样就能只允许 http://localhost:8080 这个域名的请求了
    },
     exposeHeaders: ['WWW-Authenticate','Server-Authorization'],
     maxAge:5,
     credentials:true,
     allowMethods: ['GET','POST','DELETE'],
     allowHeaders: ['Content-Type','Authorization','Accept'],
}));

资源请求:
this.$axios.post('http://172.16.186.50:3000/', {参数}) .then((response) =>{
        console.log(response)
 }) .catch(function(error){
        console.log(error);
 });

4、koa-static (静态资源服务)

npm install koa-static  --save
const path = require('path')
const static = require('koa-static')
const app = new Koa()

//设置静态资源的路径
const staticPath = './demo'
app.use(static(
    path.join( __dirname,  staticPath)
))

上一篇 下一篇

猜你喜欢

热点阅读