Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

XMLHttpRequest cannot load http://localhost:3000/players/1. Response for preflight has invalid HTTP status code 404

I am building a react-native app with rails api. I have a players_controller with create, index, update actions. I can do all things(create, index, update) from postman. But when I tried form fetch request from react action. I could only index and create player model. On update I get this error in debugger console.

:3000/players/1:1 OPTIONS http://localhost:3000/players/1
XMLHttpRequest cannot load http://localhost:3000/players/1. Response 
for preflight has invalid HTTP status code 404

in Rails my players_controller.rb

class PlayersController < ApplicationController
 skip_before_action :verify_authenticity_token
 respond_to :json
 def index
  @players = Player.find_by(player_id: params[:player_id])
  player = Player.all
  render json: @players
 end
def create
  player = Player.new(player_params)
  if player.save
    render json: player, status: 201
  else
  render json: { errors: player.errors }, status: 422
  end
end

def update
 player = Player.find(params[:id])
 player.update(player_params)
 if player.save
   render json: player, status: 201
 else
 render json: { errors: player.errors }, status: 422
 end
end

private

def player_params
 params.require(:player).permit(:username, :profile_pic, :player_id)
end
end

In my react-native app I have action

export const profilePicUpdate = (player, profile) => (dispatch) => {
const obj = player;
obj.profile_pic = profile;
fetch(`http://localhost:3000/players/${player.id}`, {
  method: 'PATCH',
  headers: {
    Accept: 'application/json',
    'Content-Type': 'application/json',
  },
  body: JSON.stringify({
    obj
  })
}).then(() => {
  dispatch({
    type: 'PROFILE_PIC_UPDATE',
    payload: profile
  });
  NavigatorService.navigate('Profile');
}).catch((error) => {
  console.log('Error', error);
});
};
like image 911
Sanjita Avatar asked Feb 25 '26 11:02

Sanjita


1 Answers

It is need to see your roues.rb file, but also maybe you need to add gem 'rack-cors' and set up it

Rails.application.config.middleware.insert_before 0, Rack::Cors do allow do origins '*' resource '*', headers: :any, methods: [:get, :post, :put, :patch, :delete, :options, :head] end end

in config/initializers/cors.rb

like image 90
dendomenko Avatar answered Feb 26 '26 23:02

dendomenko