簡體   English   中英

在 ionic 2 (angular 2) 中使用不記名令牌發布請求

[英]post request with bearer token in ionic 2 (angular 2)

我正在嘗試從 ionic2 項目向在標頭中需要不記名令牌的服務器發出發布請求。

var headers = new Headers();
headers.append('Authorization', 'Bearer '+mytoken);
let options = new RequestOptions({ headers: headers });

let body = [
  {key: 'vid',     value: myvid},
  {key: 'start_time',    value: date.toISOString()}
].map(x => `${encodeURI(x.key)}=${encodeURI(x.value)}`).join('&');

return this.http.post(mybasisurl, body, options)
      .map((res: Response) => res.json())
      .toPromise();

但它根本不起作用。 我得到 400(錯誤請求),更具體地說:

{"_body":"{\"success\":false,\"description\":\"vid not set\",\"error\":601}","status":400,"ok":false,"statusText":"Bad Request","headers":{"content-type":["application/json"]},"type":2,"url":"myurl"}

我在沒有不記名令牌的普通帖子請求中使用了類似的東西,它工作正常:

    var headers = new Headers();
headers.append('Content-Type', 'application/x-www-form-urlencoded' );
let options = new RequestOptions({ headers: headers });

let body = [
  {key: 'email',     value: email},
  {key: 'password',    value: password}
].map(x => `${encodeURI(x.key)}=${encodeURI(x.value)}`).join('&');


return this.http.post(myurl, body, options)
      .retry(NUM_HTTP_RETRIES)
      .map((res: Response) => res.json())
      .toPromise();

有什么建議?

在第二個示例中,您將內容類型標頭設置為application/x-www-form-urlencoded ,因此您需要不同格式的有效負載。

但是在第一個中,您沒有這樣做,這意味着您正在使用默認內容類型為 JSON 進行請求。

使用簡單的 JS 對象作為主體:

const body = {
  vid: myvid,
  start_time: date.toISOString()
};

@Martin Adámek 是的,你是對的。 這就是我所做的並且有效:

   var headers = new Headers();
    headers.append('Content-Type', 'application/x-www-form-urlencoded' );
    headers.append('Authorization', 'Bearer '+this.getToken());
    let options = new RequestOptions({ headers: headers });

    let body = [
      {key: 'vid',     value: vid.toString()},
      {key: 'start_time',    value: date.toISOString()}
    ].map(x => `${encodeURI(x.key)}=${encodeURI(x.value)}`).join('&');

    return this.http.post(myurl, body, options)
          .retry(NUM_HTTP_RETRIES)
          .map((res: Response) => res.json())
          .toPromise();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM