Angular8上传文件到.NETCoreAPI时出现CORS问题。
创始人
2024-10-22 15:02:10
0

CORS意指跨域资源共享,是指浏览器在发送ajax请求时,要求服务器允许当前网站跨域访问。若服务器未配置CORS,则 ajax会受到限制。本问题可通过配置ASP.NET Core API的CORS来解决。

在Startup.cs文件的ConfigureServices方法中添加以下代码:

services.AddCors(options => { options.AddPolicy("AllowAll", builder => { builder.AllowAnyHeader() .AllowAnyMethod() .SetIsOriginAllowed(_ => true) .AllowCredentials(); }); });

其中,options.PolicyName必须指定AllowAll,因为CORS策略名称是固定的。AllowAnyHeader和AllowAnyMethod表示允许发送的HTTP标头和方法。SetIsOriginAllowed方法是允许来自任何网站的发出请求。AllowCredentials允许发送cookie和身份验证标头。

在Startup.cs文件的Configure方法中的UseCors方法中添加以下代码:

app.UseCors("AllowAll");

这个代码告诉.NET Core使用先前定义的CORS策略。

在Controller中,添加[EnableCors("AllowAll")]注释以允许跨域。

在Angular项目的environment.ts文件中添加以下代码:

export const environment = { production: false, apiUrl: 'http://localhost:5000/api', baseUrl: 'http://localhost:4200', };

这样, Angular就会与API通过http://localhost:5000进行通信,而Angular本身位于http://localhost:4200。

在Angular项目的app.module.ts文件中添加以下代码:

import { HttpClientModule, HTTP_INTERCEPTORS } from '@angular/common/http'; import { MainInterceptor } from './interceptors/main.interceptor';

@NgModule({ declarations: [ AppComponent, ], imports: [ HttpClientModule, ], providers: [ { provide: HTTP_INTERCEPTORS, useClass: MainInterceptor, multi: true }, ], bootstrap: [AppComponent] }) export class AppModule { }

MainInterceptor是一个Angular拦

相关内容

热门资讯

Android Recycle... 要在Android RecyclerView中实现滑动卡片效果,可以按照以下步骤进行操作:首先,在项...
安装apache-beam==... 出现此错误可能是因为用户的Python版本太低,而apache-beam==2.34.0需要更高的P...
Android - 无法确定任... 这个错误通常发生在Android项目中,表示编译Debug版本的Java代码时出现了依赖关系问题。下...
Android - NDK 预... 在Android NDK的构建过程中,LOCAL_SRC_FILES只能包含一个项目。如果需要在ND...
Akka生成Actor问题 在Akka框架中,可以使用ActorSystem对象生成Actor。但是,当我们在Actor类中尝试...
Agora-RTC-React... 出现这个错误原因是因为在 React 组件中使用,import AgoraRTC from “ago...
Alertmanager在pr... 首先,在Prometheus配置文件中,确保Alertmanager URL已正确配置。例如:ale...
Aksnginxdomainb... 在AKS集群中,可以使用Nginx代理服务器实现根据域名进行路由。以下是具体步骤:部署Nginx i...
AddSingleton在.N... 在C#中创建Singleton对象通常是通过私有构造函数和静态属性来实现,例如:public cla...
Alertmanager中的基... Alertmanager中可以使用repeat_interval选项指定在一个告警重复发送前必须等待...