从零搭建koa服务并允许跨域

  1. 创建一个空文件夹,打开命令窗口,cd进入文件夹
  2. 运行npm init -y,初始化npm项目
  3. 运行 npm i -S koa 安装koa模块
  4. 创建 app.js 文件,内容如下
const Koa = require("koa");

const app = new Koa();

// port host
const port = process.env.PORT || 9000;
const host = process.env.host || 'localhost';

app.listen(port,host,()=>console.log("The service is running on http://"+host+":"+port));

到此一个简单的koa服务已经搭建好了,在命令窗口输入 node app.js 就可以启动服务了,下面配置路由
5. 运行 npm i -S koa-router 安装路由模块,并配置路由

const Koa = require("koa");
const Router = require("koa-router");//导入路由模块
const app = new Koa();
const router = new Router();//创建路由实例
// port host
const port = process.env.PORT || 8080;
const host = process.env.host || 'localhost';
// router
router.get("/",async ctx => {
    ctx.body = 'hello world!';
})
router.get("/hello",async ctx=>{
    ctx.body = {name:"hello"}
})
app.use(router.routes());
app.use(router.allowedMethods());

app.listen(port,host,()=>console.log("The service is running on http://"+host+":"+port));

到此路由配置结束,启动服务,在浏览器输入 http://localhost:8080 就可以看到熟悉的 hello world 了。
6. 配置跨域,安装 koa2-cors 模块,修改 app.js 如下:


const Koa = require("koa");//导入koa模块
const Router = require("koa-router");//导入路由模块
const cors = require("koa2-cors");//导入跨域模块

const app = new Koa();//创建koa实例
const router = new Router();//创建路由实例

// 定义允许跨域的origin
const allowOrigins = [
    "http://192.168.0.1:8082",
    "http://192.168.0.1:8083"
];
app.use(cors({
    origin: function(ctx) {
      if (allowOrigins.includes(ctx.header.origin)) {
        return ctx.header.origin;
      }
      return false;
    },
    exposeHeaders: ['WWW-Authenticate', 'Server-Authorization'],
    maxAge: 5,
    credentials: true,
    withCredentials:true,
    allowMethods: ['GET', 'POST', 'DELETE'],
    allowHeaders: ['Content-Type', 'Authorization', 'Accept'],
}));

// port host
const port = process.env.PORT || 9000;
const host = process.env.host || 'localhost';

// router
router.get("/",async ctx => {
    console.log(111)
    ctx.body = '{msg:"hello"}';
})
router.get("/list",async ctx=>{
    ctx.body = "helloa "
})
app.use(router.routes());
app.use(router.allowedMethods());

app.listen(port,host,()=>console.log("The service is running on http://"+host+":"+port));

至此跨域就已经配置完成了。
7. 最后配置应用程序自动重启,运行 npm i -D nodemon 安装 nodemon 模块,并且修改 package.json 文件如下:

"scripts": {
    "dev": "nodemon ./app.js"
}

直接运行 npm run dev 就可以了,每一次修改文件内容 应用程序都会自动重启。ok,结束。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值