-1

I'm trying to make a post request from an ionic2 project to a server that needs in header a bearer token.

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

but it doesn't work at all. I get 400 (Bad Request) and more specifically:

{"_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"}

I have used something similar in a normal post request without the bearer token and it was working correctly:

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

Any suggestions?

Symeon Mattes
  • 1,169
  • 16
  • 40

2 Answers2

0

In the second example, you are setting the content type header to application/x-www-form-urlencoded, so you need your payload in different format.

But in the first one, you are not doing so, meaning you are doing request with default content type being JSON.

Use simple JS object as body:

const body = {
  vid: myvid,
  start_time: date.toISOString()
};
Martin Adámek
  • 16,771
  • 5
  • 45
  • 64
0

@Martin Adámek Yes you're right. This is what I did and it worked:

   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();
Symeon Mattes
  • 1,169
  • 16
  • 40