0

When I try to make a post I'm getting a 400 (Bad Request) Error.

I'm trying to post a new Player into a Team.

My controller

def create
@teams = Team.find(params[:team_id])  
@players = @teams.players.new(player_params)
  render json: @players
end

private
 def player_params
     params.require(:player).permit(:name, :photo, :nationality)
 end

The function

_handleSubmit = async (e) => {
e.preventDefault();
const teamId = this.props.match.params.id;
const payload = this.state.players;
console.log(payload);
try {
  const res = await axios.post(`/api/teams/${teamId}/players`, payload);
} catch (err) {
  console.log(err);
 }
};

_handleChange = (e) => {
const newState = { ...this.state.players };
newState[e.target.name] = e.target.value;
this.setState({ players: newState });
};
mwlai
  • 71
  • 1
  • 9
  • If you know the request is hitting the right controller, I would check `player_params` in the controller and `payload` in your JavaScript. Since you have `player_params`, it sounds like you're using strong parameters which throws a 400 Bad Request if required parameters are missing. – Derek Hopper Apr 06 '18 at 15:25
  • I edited my functions and now I'm not getting the 400 Bad Request error but nothing is getting posted to my database. – mwlai Apr 06 '18 at 16:48
  • When you `console.log(payload)`, what does that look like? – Derek Hopper Apr 06 '18 at 16:50
  • I get exactly what I typed in the form. – mwlai Apr 06 '18 at 16:51
  • Ok, that's great. Based on your controller, it's expecting something like `{ player: { name: "", photo: "", nationality: "" }`. Is that what your server is receiving? – Derek Hopper Apr 06 '18 at 16:52
  • I don't think so. I check my api and nothing new appears. What can I do to find out? – mwlai Apr 06 '18 at 16:59
  • Have you checked your logs? You can check your development.log file to see what data is getting sent to your controller. – Derek Hopper Apr 06 '18 at 17:02
  • 1
    Ah, I just realized you're calling this `@teams.players.new(player_params)`. Calling new won't create a new player. If you want to create a record in the database, you'll want to use `@teams.players.create(player_params)` instead. – Derek Hopper Apr 06 '18 at 17:08
  • That's it! It's posting now. Except for the photo but I'll figure that out. Thanks a lot. – mwlai Apr 06 '18 at 17:19

1 Answers1

0

You need to strong compare what the body you send, and what the body you expect to receive on the server?

On backend you can send not only error code, and error message, or field identifier which error occurs.

And don't forget to set await statement if you will work with query result:

const res = await axios.post(`/api/teams/${teamId}/players`, payload);
Artem Mirchenko
  • 2,140
  • 1
  • 9
  • 21