我正在使用rails api构建一个react-native应用程序。我有一个players_controller,其中包括create、index和update操作。我可以通过postman做所有的事情(创建、索引、更新)。但是当我尝试从react action中使用fetch请求时,我只能索引和创建player模型。在更新时,我在调试器控制台中收到以下错误信息。
: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
在Rails中我的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
在我的React Native应用中,我有一个动作。
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);
});
};