XMLHttpRequest无法加载http://localhost:3000/players/1。预检请求的响应具有无效的HTTP状态码404。

3

我正在使用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);
});
};

请发布你的routes.rb文件。 - moyinho20
1个回答

1
需要查看您的routes.rb文件,但也许您需要添加 gem 'rack-cors' 并设置它
在config / initializers / cors.rb中添加以下内容:
Rails.application.config.middleware.insert_before 0,Rack :: Cors do   允许做     来源'*'     资源'*',       标头:任何,       方法:[:get,:post,:put,:patch,:delete,:options,:head]   结束 end

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接