美文网首页
nodejs 搭建项目流程

nodejs 搭建项目流程

作者: 北冥有鱼_425c | 来源:发表于2019-09-25 20:28 被阅读0次

nodejs 搭建项目流程

image.png

1、搭建项目需要的插件

koa / koa-router / nodemon【-g】 / koa-body

2、引入插件

const Koa = require('koa');
const app = new Koa();
const koaBody = require('koa-Body');

3、使用插件

app.use(koaBody())

4、导入、使用跨域中间件

app.use((ctx, next) => {
  ctx.set("Access-Control-Allow-Origin", "*");
  ctx.set("Access-Control-Allow-Methods", "PUT, POST, GET, DELETE, OPTIONS");
  // 请求头设置
  ctx.set(
    "Access-Control-Allow-Headers",
    `Content-Type, Content-Length, Authorization, Accept, X-Requested-With , yourHeaderFeild,x-token,sessionToken,token`
  );
  if (ctx.method == "OPTIONS") {
    ctx.body = 200;
  } else {
    next();
  }
})

5、导入、使用兼容get和post请求的中间件

module.exports = (ctx, next) => {
    ctx.params = {
        ...ctx.request.query,
        ...ctx.request.body
   }
   next();
}

6、导入路由 【 使用之后路由才生效 】

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

const app = new Koa();
const router = new Router();

// 增加
router.all('/city/add', (ctx, next) => {
    ctx.body = '添加城市';
});
router.all('/city/getList', (ctx, next) => {
    ctx.body = '城市列表';
});
router.all('/city/update', (ctx, next) => {
    ctx.body = '更新城市';
});
router.all('/city/del', (ctx, next) => {
    ctx.body = '删除城市';
});
// 使用之后路由才生效
app.use(router.routes());

app.listen(3000, () => {
    console.log('服务已启动,在 http://localhost:3000')
});

7、创建监听

app.listen(3000,() => {
    console.log('服务以开启 http://127.0.0.1:3000')
});

相关文章

网友评论

      本文标题:nodejs 搭建项目流程

      本文链接:https://www.haomeiwen.com/subject/aapwuctx.html