ruby-on-rails - XMLHttpRequest 无法加载 http ://localhost:3000/players/1. 预检响应具有无效的 HTTP 状态代码 404

标签 ruby-on-rails react-native redux

我正在使用 rails api 构建一个 react-native 应用程序。我有一个具有创建、索引、更新操作的 players_controller。我可以从 postman 那里做所有事情(创建、索引、更新)。但是当我尝试从 react Action 中获取表单请求时。我只能索引和创建播放器模型。更新时,我在调试器控制台中收到此错误。

: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 应用程序中我有 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);
});
};

最佳答案

需要查看您的 roues.rb 文件,但也可能需要添加 gem “架子” 并设置它

Rails.application.config.middleware.insert_before 0, Rack::Cors 做 允许做 起源'*' 资源“*”, header ::任何, 方法:[:get, :post, :put, :patch, :delete, :options, :head] 结尾 结束

config/initializers/cors.rb

关于ruby-on-rails - XMLHttpRequest 无法加载 http ://localhost:3000/players/1. 预检响应具有无效的 HTTP 状态代码 404,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44841303/

相关文章:

javascript - Redux saga debounce 而不仅仅是延迟/取消

ruby-on-rails - 无法将主分支推送到 Git 中的 Heroku

javascript - onChangeText + setState 不通过深度合并更新对象值

react-native - 带有 redux 工具包的 Redux devtools 不工作

reactjs - 如何更新 React Router 中的路由而不在单页应用程序中重新安装组件?

android - 后台定期任务和通知显示

ruby-on-rails - 具有多个数据库的 Rails 装置

ruby-on-rails - 在 Rails Controller 中有条件地调用渲染 View 的方法

ruby-on-rails - 将附加参数传递给 Controller

react-native - React native iOS 应用程序 - 在 Release模式下崩溃