Axios跨域请求处理

问题背景:

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不再可用,所以跨域配置需要更改

前端配置(Vue+Axios)

在这个文件中添加配置,现在是默认配置

javascript 复制代码
const { defineConfig } = require('@vue/cli-service')
module.exports = defineConfig({
  transpileDependencies: true,
  lintOnSave: false,
})

加入配置代理

本次问题背景:

前后端分离,前端场景:localhost:8080

后端场景:localhost:8889

前端发出请求,虽然域名相同,但是端口号不同,就会被判定为跨域

所以加入了代理,把8080发出的请求代理到8889的端口(域名也是一个道理),让server认为是同一个域名,同一个port发出的请求,避免了跨域

javascript 复制代码
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)

跨域配置

java 复制代码
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 {

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**").allowedOriginPatterns("*")
                .allowedMethods("GET", "HEAD", "POST","PUT", "DELETE", "OPTIONS")
                .allowCredentials(true).maxAge(3600);
    }
    
}

测试

响应成功

相关推荐
源码获取_wx:Fegn08956 小时前
基于springboot + vue健身房管理系统
java·开发语言·前端·vue.js·spring boot·后端·spring
Mr1ght6 小时前
为什么 InheritableThreadLocal 在 Spring 线程池中“偶尔”能传递变量?——一次线程池上下文传播的误解
java·spring
摇滚侠6 小时前
面试实战 问题三十三 Spring 事务常用注解
数据库·spring·面试
JIngJaneIL6 小时前
基于Java+ vue智慧医药系统(源码+数据库+文档)
java·开发语言·前端·数据库·vue.js·spring boot
2501_916766547 小时前
【Spring框架】SpringJDBC
java·后端·spring
谷哥的小弟7 小时前
Spring Framework源码解析——ApplicationContextInitializer
java·spring·源码
+VX:Fegn08957 小时前
计算机毕业设计|基于springboot + vue图书管理系统(源码+数据库+文档)
数据库·vue.js·spring boot·后端·课程设计
黄俊懿8 小时前
【深入理解SpringCloud微服务】Seata(AT模式)源码解析——开启全局事务
java·数据库·spring·spring cloud·微服务·架构·架构师
Dwzun11 小时前
基于SpringBoot+Vue的二手书籍交易平台系统【附源码+文档+部署视频+讲解)
java·vue.js·spring boot·后端·spring·计算机毕业设计
雨中飘荡的记忆12 小时前
Spring状态机深度解析
java·后端·spring