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拦
上一篇:Angular8如何在刷新页面时保存数据?(进一步探究)
在web应用中,当用户刷新页面或关闭页面时,通常需要保留当前数据状态以供下次访问时使用。对于Angular8来说,如何实现这个功能呢?