记第一次使用axios跨域新手小白出现的问题blocked by CORS policy: Response to preflight request doesn't pass access

记录的坑和解决的方法
此处给出三种解决方式(任选一种即可),遇见的坑(自己不了解导致)将会进行标识
遇见的主要报错为has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
其中浏览器发送了两次请求,一次为profil 请求,返回码为403,ajax返回码为404

1.在前端进行解决

假如你要访问的请求地址为locolhost:8090,那么在axios的baseUrl不应配置为http://yanzw.cn:8090,亲测将会导致代理失效,你需要将baseUrl更改为其他地址或者端口,例如改为前端启动端口locolhost:8080,如若代理地址与baseUrl一致,可能出现has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource和出现pathRewrite失效的问题。
前端解决代码:
在axios的相关文件中写下baseurl,
const http=axios.create({
baseURL:'http://localhost:8080',
timeout:10000,
withCredentials:true//允许携带cookie
});

在vue.config.js中写下代理配置

module.exports = defineConfig({
  //transpileDependencies: true,
  //lintOnSave: false,//代码检查
  devServer:{
    proxy:{
      '/api':{
        target:'http://localhost:8090',
        changeOrigin:true,
        secure:false,
        pathRewrite:{
          "^/api":''
        }
      }
    }
  }
})

此时我们的请求虽然在浏览器中看来任然访问的是8080,实际8090已经接收到请求宁能正确返回请求数据。

2.在后端springboot通过配置代理进行解决

以上述例子为例,我们可在后端添加配置类,进行配置即可,前端无需处理代理,直接将baseUrl填写为后端请求地址即可,即上述示例中的8090即可。
配置类如下,需注意allowedOrigins("http://localhost:8080")里面应填写前端请求发出的地址8080,而非后端地址localhost:8090,如果写错也会报has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.错误

@SpringBootConfiguration
public class MyWebConfigurer  implements WebMvcConfigurer {

    public void addCorsMappings(CorsRegistry corsRegistry){
        /**
         * 所有请求都允许跨域,使用这种配置就不需要
         * 在interceptor中配置header了
         */
        corsRegistry.addMapping("/**")
                .allowCredentials(true)
                .allowedOrigins("http://localhost:8080")
                .allowedMethods("POST", "GET", "PUT", "OPTIONS", "DELETE")
                .allowedHeaders("*")
                .maxAge(3600);
    }

}

3.springboot后端采用@CrossOrigin注解来解决

可以将该注解写在controller类上,表示该类中接受的所有请求都允许跨域,也可以写在方法上,表示该方法接受的请求允许跨域,无需前端配置或后端添加配置类。

注:在编写代码时可以在前端进行代理解决跨域问题,在上线生产环境中,请尽量在后端处理跨域问题。