安徽省建设干校网站,专做会议发布的网站,做动态图网站有哪些,汕头网站专业制作问题背景#xff1a; vue 项目用 axios 进行请求的时候#xff0c;总是报“Access to XMLHttpRequest at ‘http://localhost:8889/api/login’ from origin ‘http://localhost:8080……’”的错误 实际上就是前后端分离的情况下#xff0c;发生了跨域的问题 跨域定义…问题背景 vue 项目用 axios 进行请求的时候总是报“Access to XMLHttpRequest at ‘http://localhost:8889/api/login’ from origin ‘http://localhost:8080……’”的错误 实际上就是前后端分离的情况下发生了跨域的问题 跨域定义 解决方案vue-cli转发SpringBoot后端配置
本次问题用到了vue-cli的请求代理devServer.proxy强烈建议查看官网vue-cli请求代理
本次问题产生背景 springboot版本2.5.0提一下这个主要是因为SpringBoot升级2.4.0之后跨域配置中的.allowedOrigins不再可用所以跨域配置需要更改
前端配置VueAxios 在这个文件中添加配置现在是默认配置
const { defineConfig } require(vue/cli-service)
module.exports defineConfig({transpileDependencies: true,lintOnSave: false,
})
加入配置代理 本次问题背景 前后端分离前端场景localhost:8080 后端场景localhost:8889 前端发出请求虽然域名相同但是端口号不同就会被判定为跨域 所以加入了代理把8080发出的请求代理到8889的端口域名也是一个道理让server认为是同一个域名同一个port发出的请求避免了跨域
const { defineConfig } require(vue/cli-service)
module.exports defineConfig({transpileDependencies: true,lintOnSave: false,devServer: {proxy: {/api: {target: http://localhost:8889/, //填写请求的目标地址将请求转发到的目标主机这样请求就会被认为是同源changOrigin: true, //允许跨域pathRewrite: {^/api: //请求的时候使用这个api就可以}}}}
})
解读一下 其他配置
至此前端配置完毕看一下请求的方法
后端配置SpringBoot
跨域配置
package com.cc.blog.admin.config;import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;Configuration
public class WebMvcConfiguration implements WebMvcConfigurer {Overridepublic void addCorsMappings(CorsRegistry registry) {registry.addMapping(/**).allowedOriginPatterns(*).allowedMethods(GET, HEAD, POST,PUT, DELETE, OPTIONS).allowCredentials(true).maxAge(3600);}}
测试
响应成功