I want to sent an object from reactjs (frontend) to Spring boot application(backened) through POST api. For this I used fetch and json.stringfy.
myfunction(firstname, lastname, email, password, callback){
const data = {
firstname: firstname,
lastname: lastname,
email: email,
password: password
};
fetch("http://localhost:8080/data/somedata", {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify({data})
}).then(response => {
if (response.status === 200) {
console.log("Response ::", response.data);
} else {
callback(false, response.error);
}
});
}
In the backend side I have Spring boot application exposing POST api,
@RequestMapping(value ="/somedata", method = RequestMethod.POST)
public @ResponseBody String addSome (@RequestBody Map<String,String> payload) {
User n = new User();
n.setFirstName(payload.get("firstname"));
n.setLastName(payload.get("lastname"));
n.setPassword(passwordEncoder.encode(payload.get("password")));
n.setEmail(payload.get("email"));
userRepository.save(n);
return "Saved User";
}
When I invoke api over POSTMAN, it works fine. The issue is that json.stringify(data) is not giving expected result.
JSON stringified data ::: {"firstname":"testname","email":{"__reactInternalInstance$uzhpqmwh4k":{"tag":5,"key":null,"type":"input","stateNode":"~email","return":{"tag":5,"key":null,"type":"div","stateNode":{"__reactInternalInstance$uzhpqmwh4k":"~email~__reactInternalInstance$uzhpqmwh4k~return","__reactEventHandlers$uzhpqmwh4k":{"className":"col-75","children":{"type":"input","key":null,"ref":null,"props":{"className":"form-input","type":"text","id":"email","value":""},"_owner":{"tag":2,"key":null,"stateNode":{"props":{"data":{"fullname":"testname","username":"","password":"test","email":"test@testmail.com"},......
I tried to use the below. Still, the json stringified data has unnecessary characters. JSON.stringify(data, getCircularReplacer())
const getCircularReplacer = () => {
const seen = new WeakSet();
return (key, value) => {
if (typeof value === "object" && value !== null) {
if (seen.has(value)) {
return;
}
seen.add(value);
}
return value;
};
};
Can anyone please help me?
I think one of my variables are of type object. I changed it to type string and the code works fine
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.