在离子2(角度2)中使用持票人令牌发出请求

时间:2017-10-29 17:36:28

标签: angular ionic2 http-headers bearer-token

我试图将一个来自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();

有什么建议吗?

2 个答案:

答案 0 :(得分:0)

在第二个示例中,您要将内容类型标题设置为application/x-www-form-urlencoded,因此您需要使用不同格式的有效内容。

但是在第一个中,您没有这样做,这意味着您正在使用默认内容类型为JSON的请求。

使用简单的JS对象作为正文:

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

答案 1 :(得分:0)

@MartinAdá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();
相关问题