Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How send post with form-data in angular2

Tags:

post

angular

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>
like image 898
christophebazin Avatar asked Mar 17 '17 10:03

christophebazin


3 Answers

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;
            }
        );
like image 87
Venkateswaran R Avatar answered Oct 19 '22 02:10

Venkateswaran R


@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": {}
  }
}
like image 35
christophebazin Avatar answered Oct 19 '22 03:10

christophebazin


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

like image 1
Suraj Rao Avatar answered Oct 19 '22 02:10

Suraj Rao