Ruby on rails 无法加载XMLHttpRequesthttp://localhost:3000/players/1. 飞行前的响应具有无效的HTTP状态代码404
我正在用rails api构建react本机应用程序。我有一个带有创建、索引和更新操作的players\u控制器。我可以从邮递员那里做所有的事情(创建、索引、更新)。但当我尝试从react action获取表单请求时。我只能索引和创建玩家模型。更新时,我在调试器控制台中遇到此错误Ruby on rails 无法加载XMLHttpRequesthttp://localhost:3000/players/1. 飞行前的响应具有无效的HTTP状态代码404,ruby-on-rails,react-native,redux,Ruby On Rails,React Native,Redux,我正在用rails api构建react本机应用程序。我有一个带有创建、索引和更新操作的players\u控制器。我可以从邮递员那里做所有的事情(创建、索引、更新)。但当我尝试从react action获取表单请求时。我只能索引和创建玩家模型。更新时,我在调试器控制台中遇到此错误 :3000/players/1:1 OPTIONS http://localhost:3000/players/1 XMLHttpRequest cannot load http://localhost:3000/pl
: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 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
它需要查看您的roues.rb文件,但也可能需要添加 宝石“机架cors” 并设置它
Rails.application.config.middleware.insert_在0之前,Rack::Cors do
允许做
起源“*”
资源“*”,
标题::任何,
方法:[:获取,:发布,:放置,:修补,:删除,:选项,:头]
结束
结束
请在
config/initializers/cors.rb
中发布您的routes.rb
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);
});
};