当前位置: 代码迷 >> 综合 >> Vue项目启动报错: No ‘Access-Control-Allow-Origin‘ header
  详细解决方案

Vue项目启动报错: No ‘Access-Control-Allow-Origin‘ header

热度:38   发布时间:2023-09-29 06:54:31.0

     刚开始学前端知识,在调用后端接口时出现:报错 

      has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource。

我的前后端时分开的,前端端口是8080,后端服务的端口是999。http请求是由axio来实现的。

import request from '@/utils/AxiosHttpUtil';export default {getTableInfos(params) {let result = request({ url: 'http://localhost:9999/nodejs-service/nodejs/getList', method: 'get', params: params });return result;},page(params) {let result = request({ url: 'http://localhost:9999/nodejs-service/nodejs/page', method: 'post', data: params });return result;},submitData(params) {let result = request({ url: 'http://localhost:9999/nodejs-service/nodejs/formSubmit', method: 'post', data: params });return result;},getDocxData(params){let result = request({ url: 'http://localhost:9999/nodejs-service/nodejs/getFileData?' + params, method: 'get',responseType: 'blob' });return result;}
}

      在接口调用的时候就出现了,报错: .....has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource

     最后发现是跨域的问题。经过尝试目前发现有三种方式可以解决。

第一种:

        实现在返回的response中加入请求头。

@GetMapping("/getList")public List<UserInfoDto> getMethod(HttpServletRequest request, HttpServletResponse response){response.setHeader("Access-Control-Allow-Origin", "*");return Arrays.asList(new UserInfoDto("root","root", new Date(), "111111"),new UserInfoDto(), new UserInfoDto(UUID.randomUUID().toString(),"zhang", new Date(), "22222"),new UserInfoDto(),new UserInfoDto(), new UserInfoDto(), new UserInfoDto());}

这种方法要求每一个后端接口(可以跨域的接口)都需要加入代码。比较麻烦。

第二种:

后端配置统一的允许跨域的接口。

@Configuration
public class InterceptorConfigure extends WebMvcConfigurerAdapter {@Overridepublic void addCorsMappings(CorsRegistry corsRegistry){/*** 所有请求都允许跨域,使用这种配置就不需要* 在interceptor中配置header了*/corsRegistry.addMapping("/**")     //接口匹配.allowCredentials(true).allowedOrigins("*").allowedMethods("POST", "GET", "PUT", "OPTIONS", "DELETE").allowedHeaders("*").maxAge(3600);}
}

这种方法比较实用,但是需要修改后端代码。

第三种:

前端配置跨域请求。

首先需要下载 http-proxy-middleware ,在项目下执行命令:

npm install http-proxy-middleware -save-dev

然后在项目的从config下建立一个proxyConfig.js文件。内容如下:

module.exports = {proxyList:{"/nodejs-service":{target:"http://localhost:9999",   //目的地的地址,需要有http://changeOrigin:true,    //必须,允许跨域pathRewrite:{  //重写路径//如://不配置,则表示接口路径不变直接转发到指定的  服务http://localhost:9999上//  '^/nodejs-service/oldpath':'/nodejs-service/new-path',//  '^/nodejs-service':'',}}}
}

 然后在config的目录下的index.html中加入以下配置

定义变量:
const proxyConfig = require('./proxyConfig')

在dev下加入:
proxyTable: proxyConfig.proxyList,

Vue项目启动报错: No ‘Access-Control-Allow-Origin‘ header

 改变自己调用接口的地址,去掉IP信息:

import request from '@/utils/AxiosHttpUtil';export default {getTableInfos(params) {let result = request({ url: '/nodejs-service/nodejs/getList', method: 'get', params: params });return result;},page(params) {let result = request({ url: '/nodejs-service/nodejs/page', method: 'post', data: params });return result;},submitData(params) {let result = request({ url: '/nodejs-service/nodejs/formSubmit', method: 'post', data: params });return result;},getDocxData(params){let result = request({ url: '/nodejs-service/nodejs/getFileData?' + params, method: 'get',responseType: 'blob' });return result;}
}

这样就完成了。

  相关解决方案