我如何解决反应弹簧启动CORS问题?



这是我的春季启动CORS过滤器类:

@Component
public class CorsingFilter {
@Bean
public CorsFilter corsFilter() {
final UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
final CorsConfiguration config = new CorsConfiguration();
config.setAllowCredentials(true);
// Don't do this in production, use a proper list  of allowed origins
config.setAllowedOrigins(Collections.singletonList("http://localhost:3000"));
config.setAllowedHeaders(Arrays.asList("Origin", "Content-Type", "Accept"));
config.setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "OPTIONS", "DELETE", "PATCH"));
source.registerCorsConfiguration("/**", config);
return new CorsFilter(source);
}
}

这是我的控制器

@RestController
@RequestMapping("/test")
public class TestController {
@CrossOrigin(origins = "http://localhost:3000")
@GetMapping("/cox")
public String getCox(){
return "COX";
}
}

这是我的反应请求:

let url = "http://localhost:8080/test/cox";
const agent = new https.Agent({
rejectUnauthorized: false
});
try {
const res = await axios.get(url, {
auth: {
username: 'user',
password: '123456'
}
,
headers: {
'Content-Type': 'application/json',
"Access-Control-Allow-Origin": "http://localhost:8080",
'Access-Control-Allow-Credentials': true,
"Access-Control-Allow-Methods": 'HEAD, GET, POST, PUT, PATCH, DELETE',
"Access-Control-Allow-Headers": 'Origin, Content-Type, X-Auth-Token',
},
httpsAgent: agent
})
console.log(res)
} catch (err) {
console.log(err)
}

下面是浏览器错误的样子
请求是这样的

同样,当在浏览器中执行请求时(从浏览器访问localhost:8080)

假设

  1. React应用程序是使用create-react-app
  2. 创建的
  3. 前端和后端将部署在生产环境中的同一台服务器上。

解决方案

  1. 在React app的package.json中添加"proxy": "http://localhost:8080"
  2. url修改为/test/cox

https://create-react-app.dev/docs/proxying-api-requests-in-development

注意,其他流行的React框架,如Gatsby和Next.js也有类似的设置,这里的关键字是"proxy"

相关内容

  • 没有找到相关文章

最新更新