欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

springboot+vue項(xiàng)目怎么解決跨域問題詳解

 更新時(shí)間:2025年05月13日 08:54:55   作者:云之兕  
這篇文章主要介紹了springboot+vue項(xiàng)目怎么解決跨域問題的相關(guān)資料,包括前端代理、后端全局配置CORS、注解配置和Nginx反向代理,并總結(jié)了每種方法的適用場景、優(yōu)點(diǎn)和缺點(diǎn),文中通過代碼介紹的非常詳細(xì),需要的朋友可以參考下

1. 前端代理(開發(fā)環(huán)境推薦)

適用場景:Vue 開發(fā)環(huán)境調(diào)試時(shí),避免直接請(qǐng)求后端接口的跨域問題。

實(shí)現(xiàn)步驟

  • 在 Vue 項(xiàng)目的 vue.config.js 中配置代理:

    module.exports = {
      devServer: {
        proxy: {
          '/api': {  // 代理所有以 /api 開頭的請(qǐng)求
            target: 'http://localhost:8080', // Spring Boot 后端地址
            changeOrigin: true, // 允許跨域
            pathRewrite: {
              '^/api': '' // 去除請(qǐng)求路徑中的 /api 前綴
            }
          }
        }
      }
    }

    2.前端請(qǐng)求時(shí)使用 /api 前綴:

    axios.get('/api/users').then(response => {
      // 處理響應(yīng)
    });

    優(yōu)點(diǎn):無需修改后端代碼,適合開發(fā)階段快速解決跨域。

2. 后端全局配置 CORS(生產(chǎn)環(huán)境推薦)

適用場景:生產(chǎn)環(huán)境需要后端直接支持跨域。
實(shí)現(xiàn)步驟

  • 在 Spring Boot 中創(chuàng)建全局 CORS 配置類:

    @Configuration
    public class CorsConfig implements WebMvcConfigurer {
    
        @Override
        public void addCorsMappings(CorsRegistry registry) {
            registry.addMapping("/**") // 所有接口
                    .allowedOrigins("http://localhost:5173") // 允許的前端地址
                    .allowedMethods("GET", "POST", "PUT", "DELETE") // 允許的請(qǐng)求方法
                    .allowedHeaders("*") // 允許的請(qǐng)求頭
                    .allowCredentials(true) // 允許發(fā)送 Cookie
                    .maxAge(3600); // 預(yù)檢請(qǐng)求緩存時(shí)間(秒)
        }
    }

    2.若使用 Spring Security,需額外放行 OPTIONS 請(qǐng)求(預(yù)檢請(qǐng)求):

    @Configuration
    @EnableWebSecurity
    public class SecurityConfig {
    
        @Bean
        public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
            http.cors() // 啟用 CORS
                .and()
                // 其他安全配置...
                .authorizeRequests()
                .requestMatchers(HttpMethod.OPTIONS).permitAll() // 放行 OPTIONS 請(qǐng)求
                .anyRequest().authenticated();
            return http.build();
        }
    }

3. 后端注解配置(按接口控制)

適用場景:僅特定接口需要跨域支持。

實(shí)現(xiàn)步驟:在 Controller 或方法上添加 @CrossOrigin 注解:

@RestController
@CrossOrigin(origins = "http://localhost:5173") // 類級(jí)別注解
public class UserController {

    @GetMapping("/users")
    @CrossOrigin(origins = "http://localhost:5173") // 方法級(jí)別注解
    public List<User> getUsers() {
        // 業(yè)務(wù)邏輯
    }
}

4. Nginx 反向代理(生產(chǎn)環(huán)境終極方案)

適用場景:前后端部署到同一域名下,徹底避免跨域。

實(shí)現(xiàn)步驟

  • 配置 Nginx,將前端請(qǐng)求代理到后端接口:

    server {
        listen 80;
        server_name your-domain.com;
    
        # 前端靜態(tài)資源
        location / {
            root /path/to/vue/dist;
            index index.html;
            try_files $uri $uri/ /index.html;
        }
    
        # 后端 API 代理
        location /api {
            proxy_pass http://localhost:8080;
            proxy_set_header Host $host;
            proxy_set_header X-Real-IP $remote_addr;
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        }
    }

    2.重啟 Nginx:

    sudo nginx -s reload

總結(jié)

方案適用場景優(yōu)點(diǎn)缺點(diǎn)
前端代理開發(fā)環(huán)境無需后端改動(dòng),快速解決跨域僅適用于開發(fā)環(huán)境
后端全局 CORS生產(chǎn)環(huán)境統(tǒng)一管理,安全性可控需后端配置
注解配置特定接口跨域靈活控制單個(gè)接口配置冗余,維護(hù)成本高
Nginx 反向代理生產(chǎn)環(huán)境部署徹底解決跨域,提升性能需運(yùn)維支持

推薦組合

  • 開發(fā)環(huán)境:前端代理(方案1) + 后端全局 CORS(方案2)。

  • 生產(chǎn)環(huán)境:Nginx 反向代理(方案4) + 后端全局 CORS(方案2,雙重保障)。

到此這篇關(guān)于springboot+vue項(xiàng)目怎么解決跨域問題的文章就介紹到這了,更多相關(guān)springboot+vue解決跨域問題內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評(píng)論