v v
v v

Reputation: 653

Can't access API developed by rails from react-admin

In the rails app, using this file:

config/initializers/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

This backend ran at http://localhost:3001.

At frontend, in the react-admin source:

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;

It ran at http://localhost:3000.

When access frontend http://localhost:3000/#/posts, got error from chrome browser console:

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?"

Even set expose: ['X-Total-Count'] at backend, it also said missing. Why?

Upvotes: 0

Views: 1514

Answers (2)

dannyxu
dannyxu

Reputation: 571

try this:

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

It works for me!

Upvotes: 0

Shawn K
Shawn K

Reputation: 778

Take a look at the documentation on data providers. https://marmelab.com/admin-on-rest//RestClients.html

Your rails likely isn't compatible with the jsonServerProvider provider which you're trying to use. The jsonServerProvider isn't meant for production usage. It's more as a test/example provider for json-server compatible fake rest endpoints.

You'll need to write your own transport if one of the pre-built providers don't suite your needs. It's very easy.

Upvotes: 1

Related Questions