如何在angular 5中发出POST请求
这是下面的请求如何在angular 5中发出POST请求,angular,angular5,angular6,Angular,Angular5,Angular6,这是下面的请求 this.http.post('http://localhost:8989/anchor_web_api/resources', this.resourceMap).subscribe(res => console.log(res)); 我想在header中传递一些参数 如何在上述post请求中传递头请求,如授权或跨源访问控制您可以这样做 var headers = new Headers(); this.createAuthorizationHeader
this.http.post('http://localhost:8989/anchor_web_api/resources', this.resourceMap).subscribe(res => console.log(res));
我想在header中传递一些参数
如何在上述post请求中传递头请求,如授权或跨源访问控制您可以这样做
var headers = new Headers();
this.createAuthorizationHeader(headers);
headers.append('Content-Type', 'application/json');
return this.http.post(
'http://localhost:8989/anchor_web_api/resources', this.resourceMap, {
headers: headers
}).map(res => res)).subscribe(
data => { console.log(data); },
err => { console.log(err); }
);
}
您可以使用拦截器将授权令牌添加到标题中,下面是一个链接,说明如何使用拦截器写入标题->这里是Angular为了使用授权令牌,最简单和正确的方法是使用 您可以将令牌保存在本地存储中,并将其设置为随每个请求一起发送:
localStorage.setItem('token', response.access_token);
请阅读以了解如何设置令牌拦截器以及如何使用它。让我们从使用proxy.conf.json的说明开始。它通常在角度项目结构的根处创建
// proxy.config.json sample
{
"/api/": {
"target": {
"host": "localhost",
"protocol": "http:",
"port": 3000
},
"secure": false,
"changeOrigin": true,
"logLevel": "info"
}
}
然后,当您使用Angular/CLI时,可以通过以下方式调用它:
ng serve --proxy-config proxy.conf.json
Ryan Chenkie在Angular 5上有一个技术博客,但您可以在您的HttpService中使用HttpHeaders创建标题:
在使用HttpClient的HTTP请求中,向headers对象选项添加头,就像使用RxJS do将峰值添加到数据流中一样:
this._httpClient.post('url/to/api', { headers: this.headers })
.do(data => console.log(data))
;
或通过以下方式直接访问组件:
this._httpClient.post('url/to/api', { headers: this.headers })
.subscribe(data => console.log(data));
您必须创建拦截器类以在所有API中传递授权头。您无需为每个请求设置授权标头 RouteHttpInterceptor类文件
我如何在Header中设置跨源访问控制?您需要在服务器端或proxy.json中执行此操作,proxy.json文件位于我的angular project中。这不是前端,后端,您需要在服务器端管理可能重复的cors origin,不是客户端。您需要在调用的服务器上实现正确的CORS响应,客户端应用程序对此无能为力
this._httpClient.post('url/to/api', { headers: this.headers })
.subscribe(data => console.log(data));
import {Injectable} from '@angular/core';
import {Observable} from 'rxjs';
import {HttpEvent, HttpInterceptor, HttpHandler, HttpRequest} from '@angular/common/http';
import {AuthService} from '../services/auth.service';
@Injectable({
providedIn: 'root'
})
export class RouteHttpInterceptor implements HttpInterceptor {
constructor(private auth: AuthService) {
}
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
if (this.auth.token !== null) {
return next.handle(request.clone({
setHeaders: {
'Content-Type': 'application/json',
'Authorization': 'Bearer ' + this.auth.token
}
}));
}
return next.handle(request);
}
}
import {HttpHeaders} from '@angular/common/http';
const httpOptions = {
headers: new HttpHeaders({ 'Content-Type': 'application/json' })
};
const url = 'yourapi';
return this.http.post(url, {
key: 'value',
key1: 'value1'
},httpOptions);