1

network tab in console shows status 201 created I'm trying to set up a react front end for a project with a java/spring boot back end. Get requests were simple enough and I can make the POST request call but the values that are stored in the database are NULL. Quite new to react so would appreciate any help here

The react request, using axios


    import React from 'react';
import axios from 'axios';

export default class PostRequest extends React.Component {
  state = {
    firstname: '',
    lastname: '',
    biography: '',
    email: '',
  }

  handleChange = event => {
    this.setState({ firstname: event.target.value });
    this.setState({ lastname: event.target.value });
    this.setState({ biography: event.target.value });
    this.setState({ email: event.target.value });
  }

  handleSubmit = event => {
    event.preventDefault();

    const author = {
      firstname: this.state.firstname,
      lastname: this.state.lastname,
      biography: this.state.biography,
      email: this.state.email
    };

    axios.post(`http://localhost:8088/authorsrest`, { author })
      .then(res => {
        console.log(res);
        console.log(res.data);
        console.log("meh");
        console.log(author);
      })
  }

  render() {
    return (
      <div>
        <form onSubmit={this.handleSubmit}>
          <label>
            First Name:
            <input type="text" name="firstname" onChange={this.handleChange} />
          </label>
          <label>
            Last  Name:
            <input type="text" name="lastname" onChange={this.handleChange} />
          </label>
           <label>
            Last  Name:
            <input type="text" name="biography" onChange={this.handleChange} />
          </label>
           <label>
            Last  Name:
            <input type="text" name="email" onChange={this.handleChange} />
          </label>
          <button type="submit">Add</button>
        </form>
      </div>
    )
  }
}

The Post request in my controller

    @RequestMapping(method = RequestMethod.POST)
    @ResponseStatus(HttpStatus.CREATED)
    public void createNewAuthor(@RequestBody @Validated Author author) throws AuthorAlreadyRegisteredException {
        author = new Author();
        authorService.create(author);

    }

I've made all fields in the author class nullable, it's just a standard model class


import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.SequenceGenerator;

@Entity
public class Author {

    @Id
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "author_gen")
    @SequenceGenerator(name = "author_gen", sequenceName = "AUTHOR_SEQ", allocationSize = 1)
    private long authorId;

    @Column( length = 80)
    private String firstname;

    @Column( length = 80)
    private String lastname;

    @Column(length = 250)
    private String biography;

    @Column( length=50)
    private String email;



    public Author(String firstname, String lastname, String biography, String email) {
        super();
        this.firstname = firstname;
        this.lastname = lastname;
        this.biography = biography;
        this.email = email;
    }

    public Author() {
    }

    public String getFullName() {
        return this.firstname + " " + this.lastname;
    }

    public long getAuthorId() {
        return authorId;
    }

    public void setAuthorId(long authorId) {
        this.authorId = authorId;
    }

    public String getFirstname() {
        return firstname;
    }

    public void setFirstname(String firstname) {
        this.firstname = firstname;
    }

    public String getLastname() {
        return lastname;
    }

    public void setLastname(String lastname) {
        this.lastname = lastname;
    }

    public String getBiography() {
        return biography;
    }

    public void setBiography(String biography) {
        this.biography = biography;
    }



    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + (int) (authorId ^ (authorId >>> 32));
        result = prime * result + ((biography == null) ? 0 : biography.hashCode());
        result = prime * result + ((email == null) ? 0 : email.hashCode());
        result = prime * result + ((firstname == null) ? 0 : firstname.hashCode());
        result = prime * result + ((lastname == null) ? 0 : lastname.hashCode());
        return result;
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        Author other = (Author) obj;
        if (authorId != other.authorId)
            return false;
        if (biography == null) {
            if (other.biography != null)
                return false;
        } else if (!biography.equals(other.biography))
            return false;
        if (email == null) {
            if (other.email != null)
                return false;
        } else if (!email.equals(other.email))
            return false;
        if (firstname == null) {
            if (other.firstname != null)
                return false;
        } else if (!firstname.equals(other.firstname))
            return false;
        if (lastname == null) {
            if (other.lastname != null)
                return false;
        } else if (!lastname.equals(other.lastname))
            return false;
        return true;
    }

    @Override
    public String toString() {
        return "Author [authorId=" + authorId + ", firstname=" + firstname + ", lastname=" + lastname + ", biography="
                + biography + ", email=" + email + "]";
    }


}

the post request goes to the database however the fields (other than the generated id) are null

images shows null values

the console shows that the author object has values

concole output

Can anyone advise?

updating to add a screenshot of the network tab, it shows status 201 created, the database shows that the row is added - but the values are NULL

4
  • Please check the api call in network tab whether data is passed into the api or not Commented May 20, 2020 at 11:25
  • HI, I tried to add a screenshot of what I see in the network tab but I can't add it to a comment, something's passing through there, I haven't used that tab much, what should I expect to see there? Commented May 20, 2020 at 12:05
  • I took a screen shot of the network tab and added it here, it shows 201 created Commented May 20, 2020 at 12:17
  • when you work with api call you must be an expert of network tab to investigate the issue. However, as there is no option to add picture in comment, so I added the picture in answer. please check my answer Commented May 20, 2020 at 18:12

4 Answers 4

1

so I got it working with a couple of changes in the react file

import React from 'react';
import axios from 'axios';

export default class PostRequest extends React.Component {
  state = {
    author: [],
  }

  handleChange = event => {
   this.setState({[event.target.name]: event.target.value})
  }

  handleSubmit = event => {
    event.preventDefault();

    const author = {
      firstname: this.state.firstname,
      lastname: this.state.lastname,
      biography: this.state.biography,
      email: this.state.email
    };

    axios.post(`http://localhost:8088/authorsrest`, this.state)
      .then(res => {
        console.log(this.state);
        console.log(res);
        console.log(res.data);
        console.log("meh");
        console.log(author);
      })
  }

  render() {
    return (
      <div>
        <form onSubmit={this.handleSubmit}>
          <label>
            First Name:
            <input type="text" name="firstname" onChange={this.handleChange} />
          </label>
          <label>
            Last  Name:
            <input type="text" name="lastname"  onChange={this.handleChange} />
          </label>
           <label>
            Last  Name:
            <input type="text" name="biography"  onChange={this.handleChange} />
          </label>
           <label>
            Email:
            <input type="text" name="email"  onChange={this.handleChange} />
          </label>
          <button type="submit">Add</button>
        </form>
      </div>
    )
  }
}

I think the line that did the magic is

    axios.post(`http://localhost:8088/authorsrest`, this.state)

the rest is just a bit cleaner

Sign up to request clarification or add additional context in comments.

Comments

0

Are you doing anything with the received values? It looks that you are just printing them inside the async response context.

2 Comments

Yes, the POST call is doing the work, that's how the NULL values are getting into the database. The question is why are the values NULL rather than the values I'm passing in through the form
Yes I see it, you are making a POST call, and you are getting the results, in fact they are printed on the console. My question comes up because after receiving the values, you are doing anything with them. You are just calling the "console.log()". If you don´t set that value into the model you won´t have them available.
0

As you are getting null in db so first you need to check whether you are passing null value from client side or not? To check it you should open your browser console using Ctrl+Shift+I for windows and Option+Command+I for mac. Then click on Network tab and then click on the api call from left side. After that detail will be opened on right side. On Header, go down to Request Payload to check your data that you passed to api. Please check the screen (As I cannot upload screen on comment, so I put it here)

Network Tab

Comments

0

Please check your your backend code. It happens when you don't specify URL type in @CrossOrigin(origins = "{*}"). When you will use Spring Security you will automatically specify which types of URL would be allowed.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.