简体   繁体   中英

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 of 500,In angularjs I have done something like this, service file

  update: {
    method: 'POST',
    params: {
      dest1: 'update'
    },
    transformRequest: angular.identity,
    'headers': {
      'Content-Type': undefined
    }
  }

In controller as

var fd = new FormData();
var user = {
  _id: StorageFactory.getUserDetail()._id,
  loc: locDetails
};
fd.append('user', angular.toJson(user));
UserService.update(fd).
$promise.then(
  function(value) {
    console.info(value);
    updateUserDetailsInStorage();
  },
  function(err) {
    console.error(err);
  }
);

I couldn't to figure how to do this in angular 2 as angular.toJson,angular.identity and transformrequest features are not available in angular 2, so far I have done the following in angular 2,

 let fd = new FormData();
 let user = {
   _id: this.appManager.getUserDetail()._id,
   loc: locDetails
 };
 fd.append('user', JSON.stringify(user));
 this.userService.update(fd).subscribe((value) => {
   console.log(value);
   this.updateUserDetailsInStorage();
 }, (err) => {
   console.error(err);
 });

http service file

update(body) {
  console.log('update', body);
  const headers = new Headers({
    'Content-Type': undefined
  });

  const options = new RequestOptions({
    headers: headers
  });
  return this.http.post(`${app.DOMAIN}` + 'user/update', body, options)
    .map((res: Response) => {
      res.json();
    }).do(data => {
      console.log('response', data);
    })
}

I have read many posts and tried few things but so far it was unsuccessful, could anyone suggest me how to do this?

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

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");
                }
            }
        )
    });

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

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM