public void ConfigureServices(IServiceCollection services)
{
services.AddCors(o => o.AddPolicy("AllowAll", builder =>
{
builder.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader();
}));
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
app.UseCors("AllowAll");
// other middleware registration
}
import { HttpClientModule } from '@angular/common/http';
@NgModule({
imports: [
HttpClientModule
],
// ...
})
export class AppModule { }
在 app.module.ts 文件中添加了 HttpClientModule 之后,可以使用http.get()方法来从API中获取数据。在此过程中,将自动添加正确的请求头并处理跨域问题。
import { Injectable } from '@angular/core';
import { HttpInterceptor, HttpHandler, HttpRequest } from '@angular/common/http';
@Injectable()
export class AuthInterceptor implements HttpInterceptor {
constructor() { }
intercept(req: HttpRequest, next: HttpHandler) {
const authToken = localStorage.getItem('auth_token'); // replace this with your own auth token logic
if (authToken) {
const authReq = req.clone({
headers: req.headers.set('Authorization', 'Bearer ' + authToken)
});
return next.handle(authReq);
}
return next.handle(req);
}
}
将AuthInterceptor添加到您的app.module.ts模块提供商中,并在每个http请求上添加身份验证令牌。