首页 > 技术文章 > Vue SpringBoot 跨域访问

VVII 2020-04-28 13:15 原文

Vue

  • api(comApi.js)
export function testAPI (data) {
	return fetch('post','/api/getuser',data)
} 
  • 代理(config/index.js)
    port: 8080, // can be overwritten by process.env.PORT, 
    //if port is in use, a free one will be determined
    
    autoOpenBrowser: true,
    // proxyTable: {},
    proxyTable: {
        '/api': {
            target: 'http://127.0.0.1:8090/', // 后端访问域名
            changeOrigin: true,
            pathRewrite: {
                '^/api': '/' //由于后端的访问路径没有'/api',所有替换为'/'
            }
        }
    },
  • 这个是我的项目结构

SpringBoot

  • 设置允许跨域访问
@Configuration
public class CrosConfig extends WebMvcConfigurationSupport {
    //@Configuration:
    // Spring 容器在启动时,会加载默认的一些PostPRocessor,其中就有 ConfigurationClassPostProcessor,
    // 这个后置处理程序专门处理带有@Configuration注解的类,这个程序会在bean定义加载完成后,
    // 在bean初始化前进行处理。其主要处理的过程就是使用 cglib 动态代理对类进行增强,
    // 使用增强后的类替换了beanFactory原有的 beanClass,增强类会对其中带有@Bean注解的方法进行额外处理,
    // 确保调用带@Bean注解的方法返回的都是同一个实例。


    //跨域访问
    @Override
    protected void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowCredentials(true)
                .allowedHeaders("*")
                .allowedOrigins("*")
                .allowedMethods("*");
    }


}
  • 访问的接口
@RestController
public class UserController extends BaseController {
    @RequestMapping("/getuser")
    public CommonReturnType getUser(@RequestParam(required = false,name = "id") Integer id) throws BusinessException {
        UserModel userModel = userSrv.queryUserById(id);
        if (null == userModel)
            throw new BusinessException(EmBusinessError.USER_NOT_EXIST);
        System.out.println(userModel.toString());
        UserVo userVo = new UserVo();
        BeanUtils.copyProperties(userModel, userVo);
        return CommonReturnType.sendResponse(userVo);
    }
}

结果

最终很神奇的http://localhost:8080/api/getuser ==> http://localhost:8090/getuser

菜鸟小小只,也是偶然做这个,自己也是似懂非懂,仅为记录下来,免得以后忘记

推荐阅读