用koa2搭个简单服务器

const Koa = require('koa');
const Router = require('koa-router');
// 这个插件用来接收post请求传过来的参数
const bodyParser = require('koa-bodyparser');
const cors = require('koa-cors');
const fs = require('fs');

const app = new Koa();
app.use(bodyParser());
// 后端允许cors跨域请求
// app.use(cors());
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();
  }
});
const router = new Router();

// 提供一个/getJson接口
router
  .post('/api/write_map_point_json', async ctx => {
    const postParam = ctx.request.body.localPositionList;
    console.log(postParam);
    // console.log(JSON.stringify(ctx.query, null, '\t'));
    fs.writeFileSync('./public/map/json/map-point.json', JSON.stringify(postParam, null, '\t'))
    ctx.body = {
      code: 200,
      message: '请求成功'
    }

  });

const hostName = '127.0.0.1'; //本地IP
const port = 8090; //端口
// 将koa和两个中间件连起来
app.use(router.routes()).use(router.allowedMethods());
app.listen(port, hostName, () => {
  console.log(`服务运行在http://${hostName}:${port}`);
});

你可能感兴趣的:(用koa2搭个简单服务器)