0
votes

i am trying to send a post request to my spring rest api using angular and its http library.

currently in post-man (sucessfully) i am sending the data in this way:

  1. The format is form-data
  2. The key is reqData(mandatory)
  3. The Value is json(mandatory)

post-man,request

how to send the data in the same way via angular?

currently, this is how my data looks like:

onSignIn(form: NgForm) {
    const email = form.value.email;
    const password = form.value.password;

    const reqData = {
      'app_uname': email,
      'app_pass': password
    };
}

adding more about my backend code:

my rest api looks like this:

@RequestMapping(value = "/login", method = RequestMethod.POST)

@ResponseBody
public ResponseEntity<String> handle(@RequestParam(value = "reqData") String reqData,HttpServletRequest request)

so i should be sending a key and value ( i am not aware which data structure in typescript,but in java it is MultiValueMap) where the key is reqData and the value should be json in string or json object.

how to make my reqData json in angular to MultiValueMap format?

i have tried both formData and Map also:

const formData: FormData = new FormData();
    formData.append('reqData', JSON.stringify(reqData));

const map = new Map();
    map.set('reqData', reqData);
3

3 Answers

0
votes

you can create a method to post as below:

var model = {email: youremail, password: yourpassword};
post(url: string, model: any): Observable <any> {
    let formData: FormData = new FormData(); 
    formData.append('app_uname', model.email); 
    formData.append('app_pass', model.password); 
    return this._http.post(url, formData)
        .map((response: Response) => {
            return response;
        }).catch(this.handleError); 
}
0
votes

To send data to server using formdata using can do this like this

const email = form.value.email;
const password = form.value.password;

const formData: FormData = new FormData();
formData.append("email ", email);
formData.append("password ", password);

// then http post to server

Edit

if you want to submit the data as json you need to do like this

const email = form.value.email;
const password = form.value.password;

const reqData = {
  'app_uname': email,
  'app_pass': password
};

const formData: FormData = new FormData();
formData.append("reqData", JSON.stringify(reqData));

// then http post to server and in the server you need to parse the json string

Hope it solve your problem. Please let me know if this solve your problem

0
votes

This is what i have done to send request to my backend.

i created the required json,then i created a request parameter string

const reqData = 'reqData=' + jsonDataInString;

which sent a success request.