简体   繁体   中英

how to set request headers in angular2 ionic2 application

I am trying to set request headers in the http get request in an ionic2 application. The service part of the code is

import { Injectable } from '@angular/core';
import { Http, Headers, RequestOptions } from '@angular/http';
import { Observable } from 'rxjs/Rx';
import 'rxjs/add/operator/map';

// model
import { DataModel } from '../models/data.model';

@Injectable()
export class AuthService {

    constructor(private _http: Http){}

    private _url = 'https://sample.com/';

    /**
     * 
     * Request headers to set
     * Accept      : application/json
     * Content-Type: application/json
     * apiKey      : xxx
     * 
    */

    verify(): Observable<DataModel>{ 
        let headers = new Headers()
        headers.append('Accept', 'application/json'); 
        headers.append('Content-Type', 'application/json');
        headers.append('apiKey', 'xxx');

        const requestOptions = new RequestOptions({headers: headers});

        return this._http.get(this._url, requestOptions).map(data => data.json());
    }
}

Is this the proper way to implement request header. As when I tried this on an application the response was

XMLHttpRequest cannot load https://testportal.betterplace.co.in/VishwasAPI/api/public/v2/panVerification/BKCPB8852J. 
Response for preflight has invalid HTTP status code 403
EXCEPTION: Response with status: 0  for URL: null

The request/response

/**
 * Response headers
 */
HTTP/1.1 403 Forbidden
Date: Tue, 14 Mar 2017 08:11:55 GMT
Server: Apache
Access-Control-Allow-Origin: *
Access-Control-Allow-Methods: POST, GET, DELETE, PUT
Access-Control-Max-Age: 1000
Access-Control-Allow-Headers: x-requested-with, Content-Type, origin, authorization, accept, client-security-token
Content-Length: 253
Keep-Alive: timeout=15
Connection: Keep-Alive
Content-Type: text/html; charset=iso-8859-1

/**
 * Request headers
 */
OPTIONS xxx HTTP/1.1
Host: xxx
Connection: keep-alive
Access-Control-Request-Method: GET
Origin: http://localhost:8100
User-Agent: Mozilla/5.0 (iPhone; CPU iPhone OS 9_1 like Mac OS X) AppleWebKit/601.1.46 (KHTML, like Gecko) Version/9.0 Mobile/13B143 Safari/601.1
Access-Control-Request-Headers: apikey, content-type
Accept: */*
Referer: http://localhost:8100/
Accept-Encoding: gzip, deflate, sdch, br
Accept-Language: en-GB,en-US;q=0.8,en;q=0.6
AlexaToolbar-ALX_NS_PH: AlexaToolbar/alx-4.0.1

But when I tried this URL in Postman application with these request headers set, I get the proper response.

GET /xxx HTTP/1.1
Host: sample.com
Accept: application/json
Content-Type: application/json
apiKey: xxx
Cache-Control: no-cache
Postman-Token: xxx

I am stuck at this point.

I did not see any mistake in your code.But you should try this code.it is working in my app.

 getMethods(url:any) :Observable<Response>{
         let headers = new Headers();
        headers.append('Content-Type', 'application/json');  
        headers.append('x-token', localStorage.getItem('token'));  

      return this.http.get(`${API_URL2+url}`,{headers:headers})
                .map((res:Response)=>{
                         return res.json();})
                .catch((error:any)=>Observable.throw(error)||'server error');
    }

This is a CORS (cross-domain) issue. Your browser (not Angular) is sending an OPTIONS request before sending the actual POST request. Effectively, your server discards the OPTIONS request as not authenticated (or 403 forbidden in your case). Please read this answer for more info.

Have you tried to set a 'content-type' header as 'application/x-www-form-urlencoded' or 'multipart/form-data'? I think is would result in the browser not to send an OPTIONS request before sending the POST request. So, even if you solve the first problem (with the lack of OAuth header), you may still not be able to POST, because of the second problem.

You can get past CORS issues by installing the cordova Whitelist plugin

You can also try and install the Chrome Allow-Control-Origin extension .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM