post request with form-data from angular to spring

末鹿安然 提交于 2021-01-29 06:48:48

问题


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)

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

回答1:


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



回答2:


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




回答3:


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.



来源:https://stackoverflow.com/questions/55842920/post-request-with-form-data-from-angular-to-spring

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!