03-先後端分離跨域常見的3種解決方案【ZeyFra】

Git經常使用命令【ZeyFra】vue

解決先後端分離的跨域請求ios

一、SpringBoot後端配置一站式解決法~後端

/**
 * @ClassName MyWebConfigurer
 * @Description TODO
 * @date 2020/10/24 15:57
 * @created by ZeyFra
 */
@SpringBootConfiguration
public class MyWebConfiguration implements WebMvcConfigurer {
​
    // 跨域設置
    @Override
    public void addCorsMappings(CorsRegistry corsRegistry){
        corsRegistry.addMapping("/**")
                .allowCredentials(true)
                .allowedOrigins("*")
                .allowedHeaders("*")
                .allowedMethods("POST", "GET", "PUT", "OPTIONS", "DELETE")
                .exposedHeaders("access-control-allow-headers","access-control-allow-methods","access-control-allow-origin","access-control-max-age","X-Frame-Options")
                .maxAge(3600);
    }
​
}

 

二、Vue&Axios:修改vue.config.jsapi

module.exports = {
    devServer: {
      open: true,
      host: 'localhost',
      port: 8080,
      https: false,
      //以上的ip和端口是咱們本機的;下面爲須要跨域的
      proxy: {  //配置跨域
        '/api': {
          target: 'http://localhost:5001/api/',  //這裏後臺的地址模擬的;應該填寫大家真實的後臺接口
          ws: true,
          changOrigin: true,  //容許跨域
          pathRewrite: {
            '^/api': ''  //請求的時候使用這個api就能夠
          }
      }
    }
  }
}

 

三、服務器端添加響應頭跨域

response.addHeader(‘Access-Control-Allow-Origin:*’);//容許全部來源訪問 
response.addHeader(‘Access-Control-Allow-Method:POST,GET’);//容許訪問的方式
相關文章
相關標籤/搜索