简体   繁体   English

对NodeJS的React可以发布到Spring Boot REST API,但不能放入相同的API-CORS问题

[英]React on NodeJS can POST to Spring Boot REST API but can't PUT to the same API - CORS issue

My React app running on Node can make GET and POST calls to my Spring Boot REST API but when it tries to call PUT the browser console shows the OPTIONS request returning 403 and the following message in the console: 我在Node上运行的React应用程序可以对Spring Boot REST API进行GET和POST调用,但是当尝试调用PUT时,浏览器控制台会在控制台中显示OPTIONS请求返回403和以下消息:

Failed to load http://localhost:8080/project/65 : Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. 无法加载http:// localhost:8080 / project / 65 :对预检请求的响应未通过访问控制检查:所请求的资源上没有'Access-Control-Allow-Origin'标头。 Origin ' http://localhost:3000 ' is therefore not allowed access. 因此,不允许访问源' http:// localhost:3000 '。 The response had HTTP status code 403. 响应的HTTP状态码为403。

I can make the same PUT call from Postman and that works fine. 我可以从Postman拨打相同的PUT电话,效果很好。

My Spring Boot app has the following CORS configuration but this is only applies to HTML served from itself and has no impact on the React app? 我的Spring Boot应用程序具有以下CORS配置,但这仅适用于自身提供的HTML,对React应用程序没有影响吗?

@Configuration
@EnableWebMvc
public class WebConfig extends WebMvcConfigurerAdapter {

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**").allowedOrigins("http://localhost:8080", "http://localhost:3000");
    }
}

A lot of Googling of enabling CORS in Node has turned up lots of stuff about Express but this doesn't seem to help. 大量在Node中启用CORS的搜索已经发现了很多有关Express的知识,但这似乎无济于事。

As the browser works as enforcing cors, it is difficult to allow cors for localhost (from the browser). 由于浏览器用作强制执行cors,因此很难为本地主机(从浏览器)启用cors。

Btw: that's why it works with tools (except running in a browser) , as they are no browsers, no enforcing happens. 顺便说一句:这就是为什么它可以与工具(除了在浏览器中运行)一起使用的原因,因为它们不是浏览器,所以不会强制执行。

The easiest way would be to run a Middleware node express server. 最简单的方法是运行中间件节点快速服务器。

As a http server does not fill the request with cors, there should be no cors problem anymore. 由于http服务器不会用cors填充请求,因此应该不再有cors问题。

So the process would be the following: 因此,过程如下:

Frontend call request to Local http Server , Local http Server in turn makes a request to the PayPal server So: 前端呼叫请求到本地http服务器本地http服务器又向PayPal服务器发出请求,因此:

Frontend->localhttp - >PayPal server->localhttp->frontend 前端->本地​​http-> PayPal服务器->本地http->前端

Frontend and http are not same origin, so Frontend request to local http does not care about cors 前端和http的来源不同,因此对本地http的前端请求并不关心cors

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM