koa2로 간단한 서버 만들기

1485 단어
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}`);
});

좋은 웹페이지 즐겨찾기