VUE的跨域访问问题

Vue axios跨域问题
什么是跨域: 跨域请求存在的原因:由于浏览器的同源策略,即属于不同域的页面之间不能相互访问各自的页面内容。

需要在前后端都修改:步骤如下
在springboot后端:
config文件夹下(没有的新建就好)
添加class文件CORSConfig.java
内容如下
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

/**

  • @Description 跨域配置
  • @Author hejiang
  • @Date 2021/4/29 13:31
    /
    @Configuration
    public class CORSConfig extends WebMvcConfigurerAdapter{
    static final String ORIGINS[] = new String[] { “GET”, “POST”, “PUT”, “DELETE” };
    @Override
    public void addCorsMappings(CorsRegistry registry) {
    registry.addMapping("/
    ").allowedOrigins("*").allowCredentials(true).allowedMethods(ORIGINS)
    .maxAge(3600);
    }
    }

另一个文件:CORSFilter
内容如下:
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
public class CORSFilter implements Filter {

public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {
    HttpServletResponse res = (HttpServletResponse) response;
    res.addHeader("Access-Control-Allow-Credentials", "true");
    res.addHeader("Access-Control-Allow-Origin", "*");
    res.addHeader("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT");
    res.addHeader("Access-Control-Allow-Headers", "Content-Type,X-CAF-Authorization-Token,sessionToken,X-TOKEN");
    if (((HttpServletRequest) request).getMethod().equals("OPTIONS")) {
        response.getWriter().println("ok");
        return;
    }
    chain.doFilter(request, response);
}

public void destroy() {
}

public void init(FilterConfig filterConfig) throws ServletException {
}

}

然后再控制类中加上注解
@CrossOrigin

前端
import { ref } from “vue”;
import axios from “axios”;

axios.defaults.baseURL = ‘/api’;

export function postUrlAxios(url: string, data:string) {
  const result = ref(null); //后端发过来的数据
  const loading = ref(true); //加载中
  const loaded = ref(false); //加载完成了没有
  const error = ref(null); //报错

axios
    .post(url, {
      data,
    })
    .then((res) => {
      loading.value = false;
      loaded.value = true;
      result.value = res.data;
    })
    .catch((e) => {
      error.value = e;
      console.log(请求服务器失败!${e});
      loading.value = false;
    });

return {
    result,
    loading,
    loaded,
    error,
  };
}

vue.config.js
module.exports = {
  devServer: {
    proxy: {
      “/api”: {
        // 此处的写法,目的是为了 将 /api 替换成 https://www.baidu.com/
        target: “http://localhost:8001/login/”,
        // 允许跨域
        changeOrigin: true,
        ws: true,
        pathRewrite: {
          “^/api”: “”,
        },
      },
    },
  },
};

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
当前,大部分的前后端分离项目都采用Vue作为前端,Spring Boot作为后端,而VueSpring Boot本质上是两个不同的项目,它们分别运行在不同的端口上,这就导致了跨域问题的出现。 解决跨域问题可以通过以下几种方法: 1. 在Spring Boot的Controller层添加CORS配置 在Controller层的方法上添加@CrossOrigin注解,如下所示: ``` @CrossOrigin(origins = "*", maxAge = 3600) @RestController public class ApiController { //... } ``` 其中@CrossOrigin注解中的origins参数表示允许跨域访问的域名,*表示允许所有域名访问。 2. 在Spring Boot的配置文件中添加CORS配置 在Spring Boot的配置文件中添加以下配置: ``` spring: cors: allowed-origins: "*" allowed-methods: GET, POST, PUT, DELETE, OPTIONS allowed-headers: Content-Type,X-Requested-With,accept,Origin,Access-Control-Request-Method,Access-Control-Request-Headers,Authorization exposed-headers: Access-Control-Allow-Origin,Access-Control-Allow-Credentials allow-credentials: true max-age: 3600 ``` 其中allowed-origins表示允许跨域访问的域名,*表示允许所有域名访问。 3. 在Vue项目中配置代理 在Vue项目的config/index.js文件中添加以下配置: ``` proxyTable: { '/api': { target: 'http://localhost:8080', changeOrigin: true, pathRewrite: { '^/api': '' } } } ``` 其中target表示后端接口所在的地址,pathRewrite表示将请求中的/api前缀替换为空字符串。 以上三种方法都可以解决跨域问题,具体选择哪种方法可以根据实际情况来决定。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

weixin_34128593

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值