我是angular的新手,已经开始使用angular5。我想使用post方法从api获取一些数据,下面是我的代码
myhttp.interceptor.ts
import { Injectable, Injector } from '@angular/core';
import { HttpEvent, HttpInterceptor, HttpHandler, HttpRequest } from
'@angular/common/http';
import { Observable } from 'rxjs/observable';
import 'rxjs/add/observable/throw'
import 'rxjs/add/operator/catch';
@Injectable()
export class MyhttpInterceptor implements HttpInterceptor {
constructor() { }
intercept(req: HttpRequest<any>, next: HttpHandler):
Observable<HttpEvent<any>>{
const authReq = req.clone({ headers: req.headers.set("X-API-KEY",
"admin@123")});
return next.handle(authReq);
}
}
app.module.ts
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppRoutingModule,routingComponents } from './app-routing.module';
import { AppComponent } from './app.component';
import { PageNotFoundComponent } from './page-not-found/page-not-
found.component';
import { DepartmentDetailComponent } from './department-detail/department-
detail.component';
import { DepartmentOverviewComponent } from './department-
overview/department-overview.component';
import { DepartmentContactComponent } from './department-contact/department-
contact.component';
import { DepartmentdataService } from './departmentdata.service';
import {HttpClientModule,HTTP_INTERCEPTORS} from '@angular/common/http';
import {MyhttpInterceptor} from './myhttp.interceptor';
@NgModule({
declarations: [
AppComponent,
routingComponents,
PageNotFoundComponent,
DepartmentDetailComponent,
DepartmentOverviewComponent,
DepartmentContactComponent
],
imports: [
BrowserModule,
AppRoutingModule,
HttpClientModule
],
providers: [DepartmentdataService,
{
provide: HTTP_INTERCEPTORS,
useClass: MyhttpInterceptor,
multi: true
} ],
bootstrap: [AppComponent]
})
export class AppModule { }
我从这里向API请求app.component.ts
import { Component,OnInit } from '@angular/core';
import {HttpClient} from '@angular/common/http';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
title = 'routing and navigation demo';
constructor(private http: HttpClient){
}
ngOnInit(){
const req=
this.http.post('http://example.com/pcs/api/vheicles',{})
.subscribe(res => {console.log(res);},err => {console.log('Error
Occured');})
}
}
当我尝试使用以上代码时,它在控制台中显示错误- 从源“ http://example.com/pcs/api/vheicles”对“ http://localhost:4200”处XMLHttpRequest的访问已被CORS策略阻止:对预检请求的响应未通过访问控制检查:无“ Access-Control-Allow-Origin”标头存在于请求的资源上。
当我在上面的车辆api上编写代码时,我在标头中传递X-API-KEY,在这里在拦截器中传递标头,因为这是正确的,还是在拦截器中对标头的任何其他传递请帮助我。