Home > Software design >  REST react form is not working [Java Spring backend]
REST react form is not working [Java Spring backend]

Time:11-22

My Java Spring backend api is working correctly. I can create new Users using for example curl POST methods. However When I try doing the same with Form in the Browser no user is being stored in Data base. Here is the code:

class App method creates new user

// tag::create[]
onCreate(newUser) {
   follow(client, root, ['users']).then(userCollection => {
      return client({
         method: 'POST',
         path: userCollection.entity._links.self.href,
         entity: newUser,
         headers: {'Content-Type': 'application/json'}
      })
   }).then(response => {
      return follow(client, root, [
         {rel: 'users', params: {'size': this.state.pageSize}}]);
   }).done(response => {
      if (typeof response.entity._links.last !== "undefined") {
         this.onNavigate(response.entity._links.last.href);
      } else {
         this.onNavigate(response.entity._links.self.href);
      }
   });
}
// end::create[]

Here is class creating dialogue to fill in data:

// tag::create-dialog[]
class CreateDialog extends React.Component {

   constructor(props) {
      super(props);
      this.handleSubmit = this.handleSubmit.bind(this);
   }

   handleSubmit(e) {
      e.preventDefault();
      const newUser = {};
      this.props.attributes.forEach(attribute => {
         newUser[attribute] = ReactDOM.findDOMNode(this.refs[attribute]).value.trim();
      });
      this.props.onCreate(newUser);

      // clear out the dialog's inputs
      this.props.attributes.forEach(attribute => {
         ReactDOM.findDOMNode(this.refs[attribute]).value = '';
      });

      // Navigate away from the dialog to hide it.
      window.location = "#";
   }

   render() {
      const inputs = this.props.attributes.map(attribute =>
         <p key={attribute}>
            <input type="text" placeholder={attribute} ref={attribute} className="field"/>
         </p>
      );

      return (
         <div>
            <a href="#createUser">Create</a>

            <div id="createUser" className="modalDialog">
               <div>
                  <a href="#" title="Close" className="close">X</a>

                  <h2>Create new user</h2>

                  <form>
                     {inputs}
                     <button onClick={this.handleSubmit}>Create</button>
                  </form>
               </div>
            </div>
         </div>
      )
   }

}
// end::create-dialog[]

What am I doing wrong here so My POST queries end up not creating new users?

I tried to rewrite methods so They will correctly generate new Objects in database basing on input coming from client.

CodePudding user response:

OK so resolving this required from me to dive deeper into react debugging done in Developer tools in Browser. So I received such error:

"JSON parse error: Cannot coerce empty String ("") to element of `java.util.Set<com.gloss.model.EmailAddress>` (but could if coercion was enabled using `CoercionConfig`); nested exception is com.fasterxml.jackson.databind.exc.InvalidFormatException: Cannot coerce empty String ("") to element of `java.util.Set<com.gloss.model.EmailAddress>` (but could if coercion was enabled using `CoercionConfig`)
 at [Source: (org.springframework.util.StreamUtils$NonClosingInputStream); line: 1, column: 75] (through reference chain: com.gloss.model.User["emailAddress"])"

As I reviewed User model it received String which could not be mapped to an instance of an object belonging to Set data structure. The simplest solution will be to configure Jackson to accept empty Strings as null by adding this line to properties file:

spring.jackson.deserialization.accept-empty-string-as-null-object=true

This did the trick for me.

  • Related