Angular 4不包括HTTP请求的头信息。

14

我正在尝试使用简单的 Angular 4 HTTP 请求。当我检查 Chrome 开发者工具时,我无法看到 HTTP 标头。

const headers: Headers = new Headers();
headers.append('Content-Type', 'application/json');
headers.append('Authorization', 'Bearer: 123213');
this.http.post('https://127.0.0.1:502', JSON.stringify(token), {headers: headers}).subscribe();

我有什么遗漏吗?


请查看此链接:https://dev59.com/ElgR5IYBdhLWcg3wm-O6#41133924 - Max Koretskyi
@Maximus 刚刚尝试了一下,但是不起作用。 :/ - Bilal Yasar
我在我的回答中提供了一个示例,刚刚检查过,它对我有效,我正在使用Angular v4.x。 - Max Koretskyi
4个回答

24

angular@5.x. 开始,@angular/http 模块及其所有类已被弃用。现在应该使用 angular/common/http。请在这里了解更多。

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

const httpOptions = {
  headers: new HttpHeaders({
    'Content-Type':  'application/json',
    'Authorization': 'my-auth-token'
  })
};

this.http.post(
   "http://localhost:3000/contacts",
   JSON.stringify({id: 4, name: 'some'}),
   httpOptions 
).subscribe();

对于旧版本,您可以按照以下方式操作:

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

export class AppComponent {
    constructor(private http: Http) {
        const headers = new Headers();
        headers.append('Content-Type', 'application/json');
        headers.append('authentication', `hello`);

       const options = new RequestOptions({headers: headers});
       this.http.post(
           "http://localhost:3000/contacts",
           JSON.stringify({id: 4, name: 'some'}),
           options
       ).subscribe();

您必须确保@angular/http导入正确的对象:

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

如果您仍然看不到您的标头,也可能是因为您使用的服务器不允许它们。当浏览器向其他来源发出请求时,它会发送 access-control-headers-request 标头来检查服务器是否允许自定义标头。如果您的服务器未配置为允许自定义标头,则将无法在随后的请求中看到它们。


3
根据Headers文档,这个类已经被弃用,建议使用class HttpHeaders。不过我仍然无法让它正常工作,可能是因为我对语法太无知了。如果您可以更新您的答案并提供非废弃的类,我将不胜感激。 - DonkeyBanana
1
@DonkeyBanana,是的,@angular/http模块及其所有类已经被弃用了。现在应该使用@angular/common/http。我会把这个答案加上去。谢谢。 - Max Koretskyi
Headers已经过时,请使用HttpHeaders。 - Jhourlad Estrella

19

如果您使用的是HttpClient而不是Http,则代码应该像这样:

login(credintials: Authenticate): Observable<any> {

    const body = {
        username: credintials.username,
        password: credintials.password,
        grant_type: 'password',
        client_id: credintials.client_id
    };
    const headers = new HttpHeaders()
        .set('Content-Type', 'application/x-www-form-urlencoded')
        .set('Authorization', 'Basic loremlorem');

    return this.http.post(`${baseUrl}/uaa/oauth/token`,
        body,
        {
            headers: headers
        }
    );
}
如果你的params参数是可选的,那么你应该像这样附加params:
let params: HttpParams = new HttpParams();
if (param) {
  params = params.append( 'page', param.page );
}

源代码看起来像是:

/**
 * Construct a new body with an appended value for the given parameter name.
 */
append(param: string, value: string): HttpParams;

0

放置这个

constructor(private http: Http) {
            this.headers = new Headers();
            this.headers.append('content-type', 'application/json');
    }

而在该方法内部

return this.http.post(url, jsonData, this.headers).map((resp: Response) => resp.json());

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

const httpOptions = { headers: new HttpHeaders({ 'Content-Type': 'application/x-www-form-urlencoded' }) };

"用于HttpPost"

this.httpClient.post('http://localhost/rajat/ajax/contact_query_submit/',{name:name,email:email,phone:phone,message:message},httpOptions)
.subscribe(data => {
  console.log(data);
});

如果要接收POST数据,您需要执行以下步骤:

$postdata = file_get_contents("php://input");
        $_POST = json_decode($postdata,TRUE);
        $addArr = array(
            'name' => $this->input->post('name'),
            'email' => $this->input->post('email'),
            'phone' => $this->input->post('phone'),
            'message' => $this->input->post('message'),
            'created' => time()
        );

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接