搭建
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();
}
});