在之前的文章中,后端SpringBoot解决跨域问题,使用的如下方法:https://blog.terrynow.com/2021/08/18/springboot-api-allow-cross-origin-how-to/
不过前端vue也要做相应的配置,例如使用Proxy的方式请看:https://blog.terrynow.com/2021/08/31/vue-axios-cors-problem-sovled/
不过本次发现一个不使用Proxy的方式:
首先,如果不做任何修改,我们用axios请求其他链接,会报如下错误:
Access to XMLHttpRequest at 'http://192.168.1.1:8082/api/get_info' from origin 'http://localhost' has been blocked by CORS policy: The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' when the request's credentials mode is 'include'. The credentials mode of requests initiated by the XMLHttpRequest is controlled by the withCredentials attribute.
我们需要给axios来点配置
新建http.js,如果你已经有类似的配置文件(例如你配置了基准路径,或者拦截器拦截等),那么修改即可
画重点,增加:
withCredentials: false
import axios from "axios"; const service = axios.create({ baseURL: 'http://localhost:8182/api', // 基准路径 withCredentials: false, // 加上这个,解决跨域问题 timeout: 20000, }); export default service
使用的时候:
import service from "../../axios/http"; service.post();//具体axios的使用省略
文章评论