【问题标题】:how to set request headers in angular2 ionic2 application如何在 angular2 ionic2 应用程序中设置请求标头
【发布时间】:2017-10-14 03:08:35
【问题描述】:

我正在尝试在 ionic2 应用程序中的 http 获取请求中设置请求标头。代码的服务部分是

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());
    }
}

这是实现请求标头的正确方法吗?当我在应用程序上尝试此操作时,响应是

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

请求/响应

/**
 * 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

但是,当我在设置了这些请求标头的Postman 应用程序中尝试此 URL 时,我得到了正确的响应。

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

我被困在这一点上。

【问题讨论】:

    标签: http angular ionic2


    【解决方案1】:

    我在您的代码中没有发现任何错误。但是您应该尝试此代码。它在我的应用程序中运行。

     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');
        }
    

    【讨论】:

      【解决方案2】:

      这是一个 CORS(跨域)问题。您的浏览器(不是 Angular)在发送实际 POST 请求之前发送了一个 OPTIONS 请求。实际上,您的服务器将 OPTIONS 请求丢弃为未经过身份验证(或在您的情况下为 403 禁止)。请阅读this 答案以获取更多信息。

      您是否尝试将“content-type”标头设置为“application/x-www-form-urlencoded”或“multipart/form-data”?我认为这会导致浏览器在发送 POST 请求之前不发送 OPTIONS 请求。因此,即使您解决了第一个问题(缺少 OAuth 标头),您可能仍然无法 POST,因为第二个问题。

      您可以通过安装 cordova Whitelist plugin 来解决过去的 CORS 问题

      您也可以尝试安装Chrome Allow-Control-Origin extension

      【讨论】:

        猜你喜欢
        • 2016-10-15
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-03-28
        • 2018-03-30
        • 2020-10-09
        相关资源
        最近更新 更多