无法从react-admin访问rails开发的API

问题描述 投票:0回答:2

在 Rails 应用程序中,使用此文件:

配置/初始化器/cors.rb

Rails.application.config.middleware.insert_before 0, Rack::Cors do
  allow do
    origins '*'

    resource '*',
    headers: :any,
    methods: [:get, :post, :put, :patch, :delete, :options, :head],
    expose: ['X-Total-Count']
  end
end

此后端运行在 http://localhost:3001

在前端,在

react-admin
源中:

src/App.js

import React from 'react';
import { Admin, Resource } from 'react-admin';
import jsonServerProvider from 'ra-data-json-server';
import { PostList } from './posts';

const dataProvider = jsonServerProvider('http://localhost:3001');

const App = () => (
  <Admin dataProvider={dataProvider}>
    <Resource name="posts" list={PostList} />
  </Admin>
);

export default App;

它运行在 http://localhost:3000

访问前端http://localhost:3000/#/posts时,Chrome浏览器控制台出现错误:

Warning: Missing translation for key: "The X-Total-Count header is missing in the HTTP Response. The jsonServer Data Provider expects responses for lists of resources to contain this header with the total number of results to build the pagination. If you are using CORS, did you declare X-Total-Count in the Access-Control-Expose-Headers header?"

即使在后台设置了

expose: ['X-Total-Count']
,也说缺失。为什么?

ruby-on-rails cors http-headers react-admin
2个回答
1
投票

查看有关数据提供者的文档。 https://marmelab.com/admin-on-rest//RestClients.html

您的 Rails 可能与您尝试使用的

jsonServerProvider
提供商不兼容。 jsonServerProvider 不适用于生产用途。它更像是 json 服务器兼容的假休息端点的测试/示例提供程序。

如果预构建的提供程序之一不能满足您的需求,您将需要编写自己的传输。这很容易。


0
投票

试试这个:

class Api::YourResourceController < ApplicationController
  before_action :add_header

  def index
    # ...
    response.headers['X-Total-Count'] = your-records.size
    # render json data
  end

  private
  def add_header
    headers['Access-Control-Allow-Origin'] = '*'
    headers['Access-Control-Allow-Methods'] = 'POST, PUT, DELETE, GET, OPTIONS'
    headers['Access-Control-Request-Method'] = '*'
    headers['Access-Control-Allow-Headers'] = 'Origin, X-Requested-With, Content-Type, Accept, Authorization'
    headers['Access-Control-Allow-Credentials'] = 'true'
    headers['Access-Control-Expose-Headers'] = 'X-Total-Count'
  end
end

它对我有用!

© www.soinside.com 2019 - 2024. All rights reserved.