【vue】利用koa-cors实现vue-cli项目的跨域请求后端

错误提示:

Access to XMLHttpRequest at 'http://localhost:7777/charts/query' from origin 'http://localhost:8081' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: The 'Access-Control-Allow-Origin' header contains multiple values 'http://localhost:8080,http://localhost:8081', but only one is allowed.

 

原因:

跨域。vue-cli搭建的前端项目访问地址为http://localhost:8081,而当前请求接口是地址为http://localhost:7777

 

我用vue-cli搭建前端工程,后端语言则直接采用node,并调用了koa框架搭建后端

前端代码(xxx.vue):

$.ajax({
	url:'http://localhost:7777/charts/query',
	type: 'POST',
	contentType: 'application/json',
	data: JSON.stringify({}),
	dataType: 'json',
	success:function (resp) {
		console.log(resp.models);
	}
})

解决办法:

1.安装koa-cors

npm install koa-cors

2.在后端入口文件(app.js)中调用,代码如下:

后端代码(app.js):

注意:origin 需要字符串,我之前一直以为是数组也可以,因为看了一些博客都是这样写的,然后一直没成功,直到看清楚文档才发现。

/**
 * 入口文件
 *
 * Author:   gsm(qq:2479186745)
 * History:
 * Date         Version Remarks
 * ============ ======= ======================================================
 * 2019/3/27      1.0     First version
 *
 * Copyright 2016, all rights reserved. Essa.cn
 * */

// 导入koa,和koa 1.x不同,在koa2中,我们导入的是一个class,因此用大写的Koa表示:
const Koa = require('koa'),
	  routing = require('./server/router/index.js'),
	  cors = require('koa-cors');

// 创建一个Koa对象表示web app本身:
const app = new Koa();

app.use(cors({
	origin: function (ctx) {
		if (ctx.url === '/test') {
			return "*"; // 允许来自所有域名请求
		}
		return 'http://localhost:8081';
	},
	methods:['GET','POST'],
	allowHeaders: ['Content-Type', 'Authorization', 'Accept'],
}));

//路由
routing.init(app);

// 在端口3000监听:
app.listen(7777);
console.log('app started at port 7777...');

 

你可能感兴趣的:(vue,javascript,报错)