node koa2使用笔记(koa-router/koa-bodyparser)

下载依赖:

yarn add koa@2.0.0

yarn add koa-router@7.0.0  //路由匹配

yarn add koa-bodyparser  // 处理post请求

基本使用:

const Koa = require('koa');

const app = new Koa();

app.use(async (ctx, next) => {
	ctx.body = `hello koa`
})

app.listen(8000, () => {
	console.log(`run server 8000 ...`)
})

路由

const Koa = require('koa');
const router = require('koa-router')();

const app = new Koa();
// 处理 get
router.get('/index', async (ctx, next) => {
	ctx.body = `<h2>this is index page</h2>`
});
// 处理 post
router.post('/index', async (ctx, next) => {
	ctx.body = `<h2>this is index page</h2>`;
});

app.use(router.routes()); // 注册 and 使用
app.listen(8000, () => {
	console.log(`run server 8000 ...`)
})

context.request

GET
//GET
const indexFun = async (ctx, next) => {
    ctx.body = `<h3>this is</h3> <br> ${ ctx.querystring }`;
    //ctx.querystring   获取get请求的参数字符串!
    //ctx.query  获取get请求的参数对象!
}
app.use(indexFun);
POST

koa-bodyparser 来解析原始request请求,然后,把解析后的参数,绑定到ctx.request.body

//POST
const bodyParser = require('koa-bodyparser');
...
app.use(bodyParser()); //一定要在router之前注册到app对象上。

const indexFun = async (ctx, next) => {
 var name = ctx.request.body.name
    ctx.body = `<h3>this is</h3> <br> ${ name }`;
    //ctx.querystring   获取get请求的参数字符串!
    //ctx.query  获取get请求的参数对象!
}
app.use(indexFun);
...

设置跨域

中间件koa2-cors

var koa = require('koa');
var app = new koa();
var router = require('koa-router')();
// CORS是一个W3C标准,全称是"跨域资源共享"(Cross-origin resource sharing)。
// 下面以koa2-cors为例,
const cors = 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'],
}))

router.post('/', async function (ctx) {
    ctx.body = '恭喜 __小简__ 你成功登陆了'
});

app
    .use(router.routes())
    .use(router.allowedMethods());

app.listen(3000);

cors具体的实现过程


app.use(async (ctx, next) => {
    // 允许来自所有域名请求
    ctx.set("Access-Control-Allow-Origin", "*");
    // 这样就能只允许 http://localhost:8080 这个域名的请求了
    // ctx.set("Access-Control-Allow-Origin", "http://localhost:8080"); 

    // 设置所允许的HTTP请求方法
    ctx.set("Access-Control-Allow-Methods", "OPTIONS, GET, PUT, POST, DELETE");

    // 字段是必需的。它也是一个逗号分隔的字符串,表明服务器支持的所有头信息字段.
    ctx.set("Access-Control-Allow-Headers", "x-requested-with, accept, origin, content-type");

    // 服务器收到请求以后,检查了Origin、Access-Control-Request-Method和Access-Control-Request-Headers字段以后,确认允许跨源请求,就可以做出回应。

    // Content-Type表示具体请求中的媒体类型信息
    ctx.set("Content-Type", "application/json;charset=utf-8");

    // 该字段可选。它的值是一个布尔值,表示是否允许发送Cookie。默认情况下,Cookie不包括在CORS请求之中。
    // 当设置成允许请求携带cookie时,需要保证"Access-Control-Allow-Origin"是服务器有的域名,而不能是"*";
    ctx.set("Access-Control-Allow-Credentials", true);

    // 该字段可选,用来指定本次预检请求的有效期,单位为秒。
    // 当请求方法是PUT或DELETE等特殊方法或者Content-Type字段的类型是application/json时,服务器会提前发送一次请求进行验证
    // 下面的的设置只本次验证的有效时间,即在该时间段内服务端可以不用进行验证
    ctx.set("Access-Control-Max-Age", 300);

    /*
    CORS请求时,XMLHttpRequest对象的getResponseHeader()方法只能拿到6个基本字段:
        Cache-Control、
        Content-Language、
        Content-Type、
        Expires、
        Last-Modified、
        Pragma。
    */
    // 需要获取其他字段时,使用Access-Control-Expose-Headers,
    // getResponseHeader('myData')可以返回我们所需的值
    ctx.set("Access-Control-Expose-Headers", "myData");

    await next();
})

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值