5

I try to post datas with angular2 but i have a 400 bad request when i'm trying to post... With test in postman, everthing is ok, I have a 200 and success

I have a 200 and success...

But, with angular2

with angular2

I have a 400 bad request What i'm doing wrong ? Thank you !

My code. Service to call API :

userAddReview(paramsObj) {
    let headers = new Headers();
    headers.append('Content-Type', 'application/json; charset=UTF-8');
    let params = this.util.transformRequest(paramsObj);
    console.log('sending request');
    return this.authHttp.post(this.wpApiURL + '/users-reviews/reviews?' + params, JSON.stringify({}), { headers: headers })
        .map(
            res => {
                let newReview = res.json();
                this.reviews.push(newReview);
                console.log(this.reviews);
                return newReview;
            }
        );
}

Post component :

submitReview(form) {
    console.log(this.review, form);
    let params = {
        id: this.review.post,
        user_id: this.wp.getCurrentAuthorId(),
        name: this.wp.getCurrentAuthorId(),
        email: this.wp.getCurrentAuthorId(),
        title:  this.review.rating_title,
        description: this.review.rating_comment,
        rating:     this.review.rating_score,
    };
    console.log("Review", params);
    this.review.author = this.wp.getCurrentAuthorId();
    this.wp.userAddReview(params)
            .subscribe(
                data => {
                    this.statusMessage = "Review added successfully!";
                    //clear form
                    form.reset();
                },
                error => {
                    console.log(error._body);
                    this.statusMessage = error._body;
                }
    );

Template :

<form name="reviewForm" #reviewForm="ngForm" novalidate *ngIf="showPanel()">
    <div *ngIf="!reviewText.valid && (reviewText.dirty || reviewText.touched)" class="alert alert-danger padding">review is required</div>

    <div class="padding">{{statusMessage}}</div>
    <ion-input type="text" [(ngModel)]="review.rating_score" #reviewScore="ngModel" name="reviewScore" placeholder="enter your review score..." required></ion-input>
    <ion-input type="text" [(ngModel)]="review.rating_title" #reviewTitle="ngModel" name="reviewTitle" placeholder="enter your review title..." required></ion-input>
    <ion-textarea
        [(ngModel)]="review.rating_comment"
        #reviewText="ngModel"
        name="reviewText"
        type="text"
        rows="2"
        placeholder="enter your review..."
        required
        >
    </ion-textarea>

    <ion-grid>
        <ion-row>
            <ion-col *ngIf="!isEditMode"><button ion-button block (click)="submitReview(reviewForm)" [disabled]="!reviewForm.valid">Add</button></ion-col>
            <ion-col *ngIf="isEditMode"><button ion-button block (click)="updateReview(reviewForm)" [disabled]="!reviewForm.valid">Update</button></ion-col>
            <ion-col width-33><button ion-button block (click)="onCancel()">Cancel</button></ion-col>
        </ion-row>
    </ion-grid>

</form>

<p *ngIf="!showPanel() && auth.authenticated()" (click)="isEditing = true;">Add Review</p>
<p *ngIf="!auth.authenticated()" (click)="reviewFormNotAuthClicked()">Add Review (login required)</p>
Suraj Rao
  • 29,388
  • 11
  • 94
  • 103
christophebazin
  • 200
  • 2
  • 4
  • 14

3 Answers3

2

chris send the params along with header, Below is the code

let url= `${this.wpApiURLl}users-reviews/reviews`;
  let params = new URLSearchParams;
  params.append('id', id);
  params.append('user_id', user_id);
 return this.authHttp.post( url,  { headers:headers,  search:params })
.map(
            res => {
                let newReview = res.json();
                this.reviews.push(newReview);
                console.log(this.reviews);
                return newReview;
            }
        );
Venkateswaran R
  • 438
  • 2
  • 5
  • 18
  • Thank you ! But I have the same error. My request payload with your code is : {headers: {Content-Type: ["application/json; charset=UTF-8"]},…} headers : {Content-Type: ["application/json; charset=UTF-8"]} Content-Type : ["application/json; charset=UTF-8"] 0 : "application/json; charset=UTF-8" search : "id=5&user_id=1&name=1&email=1&title=sdsd&description=sdqffqs&rating=5" – christophebazin Mar 17 '17 at 11:14
  • Assign the parameters using URLSearchParams let params = new URLSearchParams; params.append('id', id); params.append('user_id', user_id); and send the params along with headers – Venkateswaran R Mar 17 '17 at 11:21
  • Thank you ! I tried, but It doesn't work, cf the next message. – christophebazin Mar 17 '17 at 13:30
  • ok... I just enter params (instead of { search : params} and it's work... – christophebazin Mar 17 '17 at 13:37
1

From the request and from the image, it looks like you are sending form data through the url rather than the body of the request. Change :

return this.authHttp.post(this.wpApiURL + '/users-reviews/reviews?' + params, JSON.stringify({}), { headers: headers })

To:

return this.authHttp.post(this.wpApiURL + '/users-reviews/reviews', params, { headers: headers })

Remember to set params as URLSearchParams object. let params = new URLSearchParams()

Suraj Rao
  • 29,388
  • 11
  • 94
  • 103
1

@Venkateswaran, nothing really better :

    let params = new URLSearchParams;
    params.append('id', '5');
    params.append('user_id', '1');
    console.log('sending request');
    return this.authHttp.post(url, { search:params })
        .map(
            res => {
                let newReview = res.json();
                this.reviews.push(newReview);
                console.log(this.reviews);
                return newReview;
            }
        )
        .subscribe(
                data => {
                    this.statusMessage = "Review added successfully!";
                    //clear form
                    form.reset();
                },
                error => {
                    console.log(error._body);
                    this.statusMessage = error._body;
                }
    );
}

And the request paylod is empty :

{
  "search": {
    "rawParams": "",
    "queryEncoder": {},
    "paramsMap": {}
  }
}
christophebazin
  • 200
  • 2
  • 4
  • 14