如何在Angular2中将Headers添加到http.get请求?

问题描述 投票:4回答:2
   import {Http, Response, Headers}          from '@angular/http'; 

getHeroes (): Observable<Heros[]> {
        return this.http.get(this.heroesUrl,  {withCredentials: true}
        )
          .map(this.extractData)
          .catch(this.handleError);
      }

不要到达标题的位置和方式。

var myHeaders = new Headers();
myHeaders.append('Access-Control-Allow-Origin', '*')

他们是如何结合的?

angular2-services
2个回答
2
投票

这是您需要向http请求添加标头的方法

import {Headers, RequestOptions} from 'angular2/http';

let body = JSON.stringify({ 'foo': 'bar' });
let headers = new Headers({ 'Access-Control-Allow-Origin': '*' });
let options = new RequestOptions({ headers: headers });

return this.http.post(url, body, options)
                .map(res =>  res.json().data)
                .catch(this.handleError)

0
投票

//可以发送单个和多个标头

import { Http, Headers, RequestOptions } from '@angular/http';

const Url = 'http://localhost:3000/';
const headers = new Headers;
const body = JSON.stringify(
{
title: "data" 
});
headers.append('Content-Type', 'application/json');
headers.append('Access-Control-Allow-Origin', '*');
this.http.post(Url, body, { headers: headers })
.pipe(map(res => res))
.catch(err => err);

// HttpHeaders in angular 5

import { HttpHeaders } from '@angular/common/http';

let header = new HttpHeaders();
header.set('Content-Type', 'application/json');
© www.soinside.com 2019 - 2024. All rights reserved.