cors 后端解决跨域问题

本文探讨了Vue项目中常见的跨域问题,特别是在本地开发环境下,8001端口尝试调用8080端口接口时遇到的CORS策略阻止问题。提供了两种有效的解决方案:一是使用@CrossOrigin注解在特定的Controller方法上;二是通过配置全局的CorsFilter过滤器来解决跨域访问限制。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

vue本地调用本地后台接口包跨域问题: 
 Access to XMLHttpRequest at 'http://localhost:8001/users' from origin 'http://localhost:8080' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

cors 跨域资源共享, 在不同服务器、端口之间进行资源访问时,会报该错误。上面的例子就是 8001端口调永8080端口的接口报错。

解决:

方法1、@CrossOrigin

在需要解决的controller方法前使用该注解

@ApiOperation(value = "用户登录")
	@ApiResponses(
			{@ApiResponse(code=200,message="成功",response = DynamicResponse.class)}
	)
	@PostMapping
	@CrossOrigin
	@ResponseBody
	public DynamicResponse<User>  login (@RequestBody LoginRequest loginRequest){

// ...
}

方法2、配置过滤器 CorsConfig

package com.lile.config;

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 {
    private CorsConfiguration buildConfig() {
        CorsConfiguration corsConfiguration = new CorsConfiguration();
        corsConfiguration.addAllowedOrigin("*");
        corsConfiguration.addAllowedHeader("*");
        corsConfiguration.addAllowedMethod("*");
        return corsConfiguration;
    }

    @Bean
    public CorsFilter corsFilter() {
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        // 配置所有请求
        source.registerCorsConfiguration("/**", buildConfig());
        return new CorsFilter(source);
    }

}

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值