vue--Cross-domain solution in practical applications

① Declare a configuration class in spring to allow access

package com.fldwws.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;

@Configuration
public class CorsConfig {
    
    
    @Bean
    public CorsFilter corsFilter() {
    
    
        //1.添加CORS配置信息
        CorsConfiguration config = new CorsConfiguration();
        //1) 允许的域,不要写*,否则cookie就无法使用了
        config.addAllowedOrigin("http://127.0.0.1:8082");
        //2) 是否发送Cookie信息
        config.setAllowCredentials(true);
        //3) 允许的请求方式GET POST等
        config.addAllowedMethod("*");
        // 4)允许的头信息
        config.addAllowedHeader("*");
        config.setMaxAge(3600L);

        //2.添加映射路径,我们拦截一切请求
        UrlBasedCorsConfigurationSource configSource = new UrlBasedCorsConfigurationSource();
        configSource.registerCorsConfiguration("/**", config);

        //3.返回新的CorsFilter.
        return new CorsFilter(configSource);
    }

}

Insert image description here

② Configure vue to allow cross-domain

2.1 vue.config.jsSet allowed cross-domain in

const {
    
     defineConfig } = require('@vue/cli-service')
module.exports = defineConfig({
    
    
  transpileDependencies: true,


  devServer: {
    
                    //webpack-dev-server配置
    host: 'localhost',
    // port: 8080,            //配置本项目运行端口
    proxy: {
    
                    //配置代理服务器来解决跨域问题
      '/api': {
    
    
        target: 'http://localhost:8081',      //配置要替换的后台接口地址
        changOrigin: true,                      //配置允许改变Origin
        pathRewrite: {
    
    
          '^/api': ''
        }
      },
    }
  },




})

Insert image description here
2.2 Initiate a request

getZhaoBiaoTable() {
    
    
            // 发送请求获取数据
            this.$axios.get("/api/zhaobiao").then(res => {
    
    
                console.log(res.data)
            })
        }

Insert image description here

get data

Insert image description here

Guess you like

Origin blog.csdn.net/weixin_44239550/article/details/128752320