1. const koa = require("koa");
    2. const router = require("koa-router")();
    3. const app = new koa();
    4. const bodyParser = require("koa-bodyparser");
    5. router.post("/login", async ctx => {
    6. // username=cheng pass=123
    7. var {username,pass} = ctx.request.body;
    8. if (username == "cheng" && pass == "123") {
    9. ctx.cookies.set("auth", true, {
    10. httpOnly: false
    11. })
    12. ctx.body = {
    13. auth: true,
    14. code: 200,
    15. msg: "登录成功"
    16. }
    17. }else{
    18. ctx.body = {
    19. code:400,
    20. msg:"登录失败"
    21. }
    22. }
    23. })
    24. app.use(async (ctx, next) => {
    25. ctx.set("Access-Control-Allow-Methods", "*")
    26. // 跨域
    27. ctx.set('Access-Control-Allow-Headers', 'Content-Type, Content-Length, Authorization, Accept, X-Requested-With , yourHeaderFeild');
    28. ctx.set("Access-Control-Allow-Origin", ctx.headers.origin);
    29. //允许跨域发送cookie请求
    30. ctx.set("Access-Control-Allow-Credentials", true)
    31. if (ctx.method == "OPTIONS") {
    32. ctx.body = 200
    33. } else {
    34. await next();
    35. }
    36. })
    37. app.use(bodyParser());
    38. app.use(router.routes());
    39. app.listen(8000);