Skip to content Skip to sidebar Skip to footer

How To Send Form Data In A Http Post Request Of Angular 2?

I am trying to send form data of the updated user details to the back end which node server in angular 2,However I couldn't send the form data and the server responds with status o

Solution 1:

You can add headers if your server controller requires it else you can simply post it like this

let body = new FormData();
body.append('email', 'emailId');
body.append('password', 'xyz');
this.http.post(url, body);

Solution 2:

This is a functional solution for build a POST request in Angular2, you don't need an Authorization header.

var headers = new Headers();
headers.append('Content-Type', 'application/x-www-form-urlencoded');

let options = new RequestOptions({ headers: headers });

var body = "firstname=" + user.firstname + "&lastname=" + user.lastname + "&username=" + user.username + "&email=" + user.email + "&password=" + user.password;

return new Promise((resolve) => {
                this.http.post("http://XXXXXXXXXXX/users/create", body, options).subscribe((data) => {
                if (data.json()) {
                    resolve(data.json());
                } else {
                    console.log("Error");
                }
            }
        )
    });

Solution 3:

Here is the method from my app which works fine.

 updateProfileInformation(user: User) {
    this.userSettings.firstName = user.firstName;
    this.userSettings.lastName = user.lastName;
    this.userSettings.dob = user.dob;

    var headers = new Headers();
    headers.append('Content-Type', this.constants.jsonContentType);

    var s = localStorage.getItem("accessToken");
    headers.append("Authorization", "Bearer " + s);
    var body = JSON.stringify(this.userSettings);

    return this.http.post(this.constants.userUrl + "UpdateUser", body, { headers: headers })
      .map((response: Response) => {
        var result = response.json();
        return result;
      })
      .catch(this.handleError)
  }

Solution 4:

Here is the method I've used in angular 4 for uploading files.... for Ui

   <input type="file"id="file"(change)="handleFileInput($event)">

and .ts file I've added this ....

  handleFileInput(event) {
    let eventObj: MSInputMethodContext = <MSInputMethodContext> event;
    let target: HTMLInputElement = <HTMLInputElement> eventObj.target;
    let files: FileList = target.files;
    this.fileToUpload  = files[0];
    console.log(this.fileToUpload);
  }



 uploadFileToActivity() {
    console.log('Uploading file in process...!' + this.fileToUpload );
    this.fontService.upload(this.fileToUpload).subscribe(
      success => {
        console.log(JSON.stringify(this.fileToUpload));
        console.log('Uploading file succefully...!');
        console.log('Uploading file succefully...!' + JSON.stringify(success));
      },
      err => console.log(err),
    );
  }

and In services

upload(fileToUpload: File) {
    const headers = new Headers({'enctype': 'multipart/form-data'});
    // headers.append('Accept', 'application/json');
    const options = new RequestOptions({headers: headers});
    const formData: FormData = new FormData();
    formData.append('file', fileToUpload, fileToUpload.name);
    console.log('before hist the service' + formData);
    return this.http
      .post(`${this.appSettings.baseUrl}/Containers/avatar/upload/`, formData , options).map(
        res => {
          const data = res.json();
          return data;
        }
      ).catch(this.handleError);
  }

This method used for single file uploading to the server directory.


Solution 5:

FINAL answer sending like below working fine .

         const input = new FormData();
            input['payload'] = JSON.stringify(param);
             console.log(input);
                  alert(input);
                return this.httpClient.post(this.hostnameService.razor + 'pipelines/' + 
                    workflowId, input).subscribe(value => {
                 console.log('response for Manual Pipeline ' + value);
                 return value;
                   }, err => {
                     console.log(err);
                     }); 

Post a Comment for "How To Send Form Data In A Http Post Request Of Angular 2?"