简体   繁体   English

使用 Fetch api DELETE 方法并启用 no-cors

[英]Using Fetch api DELETE method with no-cors enabled

I am trying to make an API requests that deletes an entity in the backend.我正在尝试发出删除后端实体的 API 请求。 My spring server and node.js server are running on different ports.我的 spring 服务器和 node.js 服务器在不同的端口上运行。

When I try a fetch request with cors enabled ( mode: "cors" ) I get an error that the request was blocked by the cors policy.当我尝试启用 cors 的获取请求( mode: "cors" )时,我收到一条错误消息,指出该请求被 cors 策略阻止。 When I disabel cors ( mode: "no-cors" ), I get the following error:当我禁用 cors ( mode: "no-cors" )时,我收到以下错误:

 Failed to execute 'fetch' on 'Window': 'DELETE' is unsupported in no-cors mode.

The code for the request:请求的代码:

export async function deleteOneProcessType(id) {
let ret = await fetch(`${restUri}${uri}/${id}`, {
    method: "DELETE",
    mode: "no-cors"
})

} }

I have similar POST and GET methods whith cors disabled that work just fine.我有类似的 POST 和 GET 方法,但 cors 禁用了它工作得很好。

No need to set mode: "no-cors" Indeed you just need toadjust your backend in order to allow your request无需设置模式:“no-cors”事实上,您只需要调整您的后端以允许您的请求

To do so add a WebMvcConfigurer Bean为此,添加一个 WebMvcConfigurer Bean

You can do so using a Configuration class for instance.例如,您可以使用配置 class 来执行此操作。 You can refer to https://spring.io/blog/2015/06/08/cors-support-in-spring-framework可以参考https://spring.io/blog/2015/06/08/cors-support-in-spring-framework

As mentionned in the documentation by default only GET and POST requests are allowed.正如文档中提到的,默认情况下只允许 GET 和 POST 请求。 Then you need to allow DELETE as well然后您还需要允许 DELETE

Finally you should have something like that:最后你应该有这样的东西:

@Bean
public WebMvcConfigurer corsController()
{
    return new WebMvcConfigurer() {
        @Override
        public void addCorsMappings(CorsRegistry registry) {
            registry.addMapping("[Your_backend_server_URI_here]/**")
                    .allowedOrigins("[Your_frontend_URL_here]")
                    .allowedMethods("PUT","DELETE","GET","POST");
        }
    };
}

POST and GET are considered simple requests where you can use mode: "no-cors" . POSTGET被认为是simple requests ,您可以在其中使用mode: "no-cors" You cannot do this with DELETE and PUT for example.例如,您不能使用 DELETE 和 PUT 执行此操作。 I suggest you to use Proxy server for all your API calls.我建议您对所有 API 调用使用Proxy server With a Proxy server you can solve CORS error.使用代理服务器,您可以解决 CORS 错误。

Example: you want to delete an entity to this api: https://test.api.com/customer/1 .示例:您要删除此 api 的实体: https://test.api.com/customer/1

In package.json add the following line:package.json添加以下行:

"proxy": "https://test.api.com"

Your request in the component:您在组件中的请求:

export async function deleteOneProcessType(id) {
let ret = await fetch(`/customer/${id}`, {
    method: "DELETE"
})

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

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