Mohy Fahim
Mohy Fahim

Reputation: 49

Http request to parse server using Angular HttpClient

I was trying to use parse server’s REST API so in it’s documentation, they wrote : To create a new object on Parse, send a POST request to the class URL containing the contents of the object. For example, to create the object described above:

curl -X POST \
-H "X-Parse-Application-Id: ${APPLICATION_ID}" \
-H "X-Parse-REST-API-Key: ${REST_API_KEY}" \
-H "Content-Type: application/json" \
-d '{"score":1337,"playerName":"Sean Plott","cheatMode":false}' \
https://YOUR.PARSE-SERVER.HERE/parse/classes/GameScore

I tested it and it worked correctly so I want to use this method by angular HttpClient, then I wrote this code :

let url = 'https://parseapi.back4app.com/classes/test';
const httpOptions = {
headers: new HttpHeaders({

  'X-Parse-Application-Id': '6mK3kDvzuLeyJojS9yRGYr6JxmuDtapGhwmUflqy',
  'X-Parse-REST-API-Key': '########################################',
  'Content-Type':  'application/json'
 })
 };
    let params = new HttpParams();
    params = params.set('score', '1337');
    params = params.append('playername', 'mohy');
    this.httpClient.post(url,params,httpOptions).subscribe(data =>{
      console.log(data);

    },err => {
      alert(err.message);
    });

}

when I used curl, it worked correctly but if I use HttpClient I get this error: Http failure response for https://parseapi.back4app.com/classes/test: 400 Bad Request

how can I fix this?

Upvotes: 2

Views: 1236

Answers (1)

Muhammed Albarmavi
Muhammed Albarmavi

Reputation: 24424

HttpParams object serialize to an encoded string URL-query-string (?score=1337&playername=mohy) format,and this not valid json format as mention by content-type.

let url = 'https://parseapi.back4app.com/classes/test';
const httpOptions = {
 headers: new HttpHeaders({
   'X-Parse-Application-Id': '6mK3kDvzuLeyJojS9yRGYr6JxmuDtapGhwmUflqy',
   'X-Parse-REST-API-Key': '########################################',
   'Content-Type':  'application/json'
  })
 };

let body = {
  score: '1337',
  playername: 'mohy'
 }

this.httpClient.post(url,JSON.stringify(body),httpOptions).subscribe(data =>{
   console.log(data);
 },err => {
      alert(err.message);
 });
}

if you want to use get method and pass the parameter as URL-query-string

 let params = new HttpParams();
    params = params.set('score', '1337');
    params = params.append('playername', 'mohy');

    this.httpClient.get(url,{params},httpOptions).subscribe(data =>{
      console.log(data);
    },err => {
      alert(err.message);
    });

Upvotes: 3

Related Questions