Koa服务器搭建及Koa跨域解决

搭建

const Koa = require("koa");
const KoaRouter = require("koa-router");

// 1.创建koa实例
const app = new Koa();
// 3.创建koa-router实例
const router = new KoaRouter();

// 3.1 使用koa-router提供的中间件
// 使用koa-router提供的中间件,使用routes以及allowedMethods函数的返回值作为中间键
app.use(router.routes()) //声明使用路由
    .use(router.allowedMethods())  //声明使用路由的方法
    
// 2.通过koa.listen()将服务器运行在某个端口上,监听

/* 3.2注册路由  
前端路由指的是路径与组件之间的映射关系
后端路由指的是路径与请求方式及回调函数的映射关系
express 路由的回调函数,接收三个参数:
	1)req -> 请求信息对象  
	2)res -> 响应信息对象 
	3)next -> 数据类型是函数,调用可以执行下一个中间键

koa 路由的回调函数,接收两个参数:
	1)ctx -> req+res
	2)next -> 数据类型是函数,调用可以执行下一个中间键 */

router.get('/test',(ctx,next)=>{
	// console.log(ctx)
	// 1.获取请求参数 query -> ctx.query  params -> ctx.params  body -> 需要安装插件
	// console.log(ctx.query)
	const id = ctx.query.id;
	// 2.处理数据
	const str = "我是返回的数据"+id
	// 3.返回响应,ctx.body=返回内容
	ctx.body=str;
})

let getCitysData = require('./datas/citylists.json');
router.get('/getCitysData', function (ctx, next) {
    ctx.body = getCitysData
})

app.listen("3000", function (error) {
    if (error) {
        console.log("服务器运行失败");
    } else {
        console.log("服务器运行成功:http://localhost:3000");
    }
})

跨域解决

1.下载@koa/cors

 npm i @koa/cors  

引入并安装

const cors = require("@koa/cors")
app.use(cors())

2.设置响应头

注意:要设置在其他中间件得前面。因为代码是从上到下执行。写在后面会导致不起作用,依然存在跨域问题。

app.use(async (ctx, next) => {
    ctx.set('Access-Control-Allow-Origin', '*');
    ctx.set('Access-Control-Allow-Headers', 'Content-Type, Content-Length, Authorization, Accept, X-Requested-With , yourHeaderFeild');
    ctx.set('Access-Control-Allow-Methods', 'PUT, POST, GET, DELETE, OPTIONS');
    if (ctx.method == 'OPTIONS') {
        ctx.body = 200;
    } else {
        await next();
    }
});
  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值