koa2-cors跨域无效?help me!

问题描述

koa2-cors跨域无效,preflight请求203,真实请求失败,求大佬看看┭┮﹏┭┮
补充:刚才换了一下提交的表格,就请求成功了,难道是{columns:Array(6),rows:Array(22049)}}这个数据太多了吗?但实际上比这还要多,要怎么处理呢?

问题出现的环境背景及自己尝试过哪些方法

app.js中三种百度到的方法都试过了,没有作用,源码链接:https://gitee.com/yellowshy/C...
%}GD4JY_%UBNW_Y6G@BM0RB.png
-
6KSYQCNN~@GX9I[$_EG[@[V.png
-
)N8YIXTcode4XQXH~/codeYTFURKNW.png
-
0WBMTLWQFA3F7`Z_MUL%EHV.png

相关代码

app.js

const path = require('path');
const Koa = require('koa');
const Router = require('koa-router');
const koaBody = require('koa-body');
const cors = require('koa2-cors');
const mongoose = require('mongoose');
const koaStatic = require('koa-static');

// 路由文件
const apiRouter = require('./routes/api');
const userRouter = require('./routes/user');
const chartRouter = require('./routes/chart');
const connectRouter = require('./routes/connect');
const demoRouter = require('./routes/demo');

const app = new Koa();
// 解析 POST 请求
app.use(koaBody({
  multipart: true, // 支持文件上传
  formidable: {
    uploadDir: path.join(__dirname, './public/upload/'), // 设置文件上传目录
    keepExtensions: true, // 保持文件的后缀
    maxFieldsSize: 2 * 1024 * 1024, // 文件上传大小
  },
}));

// 连接数据库
mongoose.connect("mongodb://localhost:27017/chartfun", { useNewUrlParser: true }, err => {
  if (err) {
    console.log('[server] MongoDB connect error: ' + err);
  } else {
    console.log('[server] MongoDB connected!');
  }
});

const router = new Router();

app.use(koaStatic(
  path.join(__dirname, './public')
))

// app.use(cors());
app.use(cors({
  origin: function (ctx) {
    console.log(ctx.url);
    console.log(ctx.header.origin);
      if (ctx.url == '/connect/') {
          return ctx.header.origin; // 允许来自所有域名请求
      }
      return 'http://localhost:8080';
  },
  exposeHeaders: ['WWW-Authenticate', 'Server-Authorization'],
  maxAge: 5,
  credentials: true,
  allowMethods: ['GET', 'POST', 'DELETE'], //设置允许的HTTP请求类型
  allowHeaders: ['Content-Type', 'Authorization', 'Accept'],
}));

// 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();
//   };
// })

router.get('/', (ctx, next) => {
  // ctx.router available
  ctx.body = 'Hello!';
});

app.use(apiRouter.routes()).use(apiRouter.allowedMethods());
app.use(userRouter.routes()).use(userRouter.allowedMethods());
app.use(chartRouter.routes()).use(chartRouter.allowedMethods());
app.use(connectRouter.routes()).use(connectRouter.allowedMethods());
app.use(demoRouter.routes()).use(demoRouter.allowedMethods());
app.use(router.routes()).use(router.allowedMethods());
app.listen(3000);

connect.js

const Router = require('koa-router');
const connectModel = require('../models/connect');

const router = new Router();
router.prefix('/connect');

// 新增数据源
router.post('/', async (ctx, next) => {
  const body = ctx.request.body;

  if (!body.name || !body.data) {
    ctx.body = {
      errno: 1,
      errmsg: '格式错误'
    }
    return;
  }

  const result = await connectModel.create({
    name: body.name,
    data: body.data,
    uid: body.uid,
  });

  ctx.body = {
    errno: 0,
    data: result
  }
});

module.exports = router;

DataAdd.vue

methods: {
    onSubmit () {
      var that = this;
      that.$refs["ruleForm"].validate(valid => {
        if (valid) {
          that
            .$confirm("确定提交吗?", "提示", {
              confirmButtonText: "确定",
              cancelButtonText: "取消",
              type: "warning",
              center: true
            })
            .then(() => {
              console.log(this.newData);
              this.$http
                .post('/connect/', {
                  name: this.form.name,
                  data: this.newData,
                  uid: this.user.uid
                })
                .then(res => {
                  const { errno, data } = res.data;
                  if (errno === 0) {
                    this.$message({
                      type: 'success',
                      message: '保存成功'
                    });
                    this.$router.push('/console/data');
                    // this.editChart(data._id);
                  }
                })
                .catch(() => {});
            })
            .catch(() => { });
        } else {
          return false;
        }
      });
      // this.$router.push('/console/data')
    }

你期待的结果是什么?实际看到的错误信息又是什么?

阅读 5.2k
1 个回答

那个app.use(cors());需要放再请求的最前面。

原因是跨域的时候,首先发起的是一个OPTION请求,如果这个请求没有正确返回,则会导致跨域失败。

需要将cors配置放在const app = new Koa();

const app = new Koa();
app.use(cors());
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题
宣传栏