Reputation: 1
I am trying to make an API requests that deletes an entity in the backend. My spring server and node.js server are running on different ports.
When I try a fetch request with cors enabled (mode: "cors"
) I get an error that the request was blocked by the cors policy. When I disabel cors (mode: "no-cors"
), I get the following error:
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.
Upvotes: -2
Views: 2703
Reputation: 29
No need to set mode: "no-cors" Indeed you just need toadjust your backend in order to allow your request
To do so add a WebMvcConfigurer Bean
You can do so using a Configuration class for instance. You can refer to 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. Then you need to allow DELETE as well
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");
}
};
}
Upvotes: 1
Reputation: 948
POST
and GET
are considered simple requests
where you can use mode: "no-cors"
. You cannot do this with DELETE and PUT for example. I suggest you to use Proxy server
for all your API calls. With a Proxy server you can solve CORS error.
Example: you want to delete an entity to this api: https://test.api.com/customer/1
.
In package.json add the following line:
"proxy": "https://test.api.com"
Your request in the component:
export async function deleteOneProcessType(id) {
let ret = await fetch(`/customer/${id}`, {
method: "DELETE"
})
Upvotes: -1