我正在尝试发出删除后端实体的 API 请求。我的 spring 服务器和 node.js 服务器运行在不同的端口上。
当我在启用了 cors 的情况下尝试提取请求时 (
mode: "cors"
),我收到一条错误消息,表明该请求被 cors 策略阻止。当我禁用 cors (mode: "no-cors"
) 时,出现以下错误:
Failed to execute 'fetch' on 'Window': 'DELETE' is unsupported in no-cors mode.
请求代码:
export async function deleteOneProcessType(id) {
let ret = await fetch(`${restUri}${uri}/${id}`, {
method: "DELETE",
mode: "no-cors"
})
}
我有类似的 POST 和 GET 方法,但禁用了 cors,效果很好。
无需设置模式:“no-cors” 事实上,您只需要调整您的后端即可允许您的请求
为此添加 WebMvcConfigurer Bean
例如,您可以使用配置类来执行此操作。 您可以参考https://spring.io/blog/2015/06/08/cors-support-in-spring-framework
正如文档中提到的,默认情况下仅允许 GET 和 POST 请求。 然后你还需要允许删除
最后你应该有这样的东西:
@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
和 GET
被视为 simple requests
,您可以在其中使用 mode: "no-cors"
。例如,您不能使用 DELETE 和 PUT 来执行此操作。我建议您对所有 API 调用使用 Proxy server
。使用代理服务器可以解决 CORS 错误。
示例:您要删除此 api 的实体:
https://test.api.com/customer/1
。
在 package.json 添加以下行:
"proxy": "https://test.api.com"
您在组件中的请求:
export async function deleteOneProcessType(id) {
let ret = await fetch(`/customer/${id}`, {
method: "DELETE"
})