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);
    }
    
}

测试

响应成功

相关推荐
猿究院_夏燊2 小时前
Spring Bean 生命周期
java·后端·spring
gc_22993 小时前
Vue框架学习(1:环境搭建)
vue.js
流烟默3 小时前
MCP第 5 篇:用 Spring AI 写 MCP:注解、自动配置、ChatClient 集成
人工智能·spring·mcp封装
来福猿6 小时前
SpringCloud Config 源码分析:配置拉取、刷新与多环境管理
后端·spring·spring cloud
我的div丢了肿么办8 小时前
element-plus表格使用:filter-method过滤导致出现无数据
前端·javascript·vue.js
贾公子9 小时前
AI 内容检测 API 接入实战——异步任务、幂等键与轮询的正确写法
vue.js
雷一言说9 小时前
Spring AI 2.0 RAG:用 Metadata Filter 做多租户检索隔离
java·spring
星光不问赶路人9 小时前
Vue 项目类型检查:深入理解 vue-tsc --build
前端·vue.js
WeiXin_DZbishe9 小时前
基于springboot装修风格选择系统的设计与开发-计算机毕设【课程设计】77964
java·vue.js·spring boot·后端·python·php·课程设计
摇滚侠10 小时前
《大模型应用开发实践:基于 Spring AI+DeepSeek 实现》第 11 章 大模型技术概览 阅读笔记 1
人工智能·笔记·spring