如何解决React-Admin 自定义 api 调用
我正在尝试将 react-admin 用于我的管理仪表板(React+NodeJS) 我尝试使用的 api 是
http://localhost:8000/api/v1/countries
这是json响应:
{
"error": "false","data": [
{
"country_name": "Afghanistan","country_capital": "Kabul","country_area": "652230","country_currency": "Afghani افغانی","continent": "Asia"
},{
"country_name": "Bhutan","country_capital": "Thimphu","country_area": "38,394","country_currency": "Ngultrum (BTN)",.........
]
}
想法是在 Admin Dashboard 中实现基本的 CRUD 操作
这是我的 Dashboard.js 组件
import * as React from "react";
import { Admin,Resource } from 'react-admin';
import simpleRestProvider from 'ra-data-simple-rest';
import {CountryList} from '../../Components/Country/Country';
const Dashboard = () => (
<Admin title="My Custom Admin" dataProvider={simpleRestProvider('http://localhost:8000/api/v1/countries')}>
<Resource name="Countries" list={CountryList} />
</Admin>
);
export default Dashboard
我的country.js如下
import * as React from "react";
import { List,Datagrid,TextField,EmailField } from 'react-admin';
export const CountryList = props => (
<List {...props}>
<Datagrid rowClick="edit">
<TextField source="country_name" />
<TextField source="country_name" />
<TextField source="country_area" />
<TextField source="country_currency" />
<TextField source="continent" />
</Datagrid>
</List>
);
最后的api如下:
app.get("/api/v1/countries",async (request,response) => {
try{
const countries = await database.query(
`SELECT * FROM COUNTRIES`,);
response.status(200);
if(countries.length > 0)
{
response.json({
error: "false",data: countries
});
}
else{
response.json({
error: "true"
})
}
}
catch (e) {
response.status(500);
response.json(e);
}
});
}
在 index.js 中
app.use(bodyParser.urlencoded({ extended: true }));
app.use(express.json());
app.use(cors());
这是我得到的错误:
The Content-Range header is missing in the HTTP Response. The simple REST 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 Content-Range in the Access-Control-Expose-Headers
header?
那么,我在这里做错了什么? 我需要重新编写我的 api 还是与数据提供者有关?
解决方法
服务器响应必须包含标头:“Content-Range”表示集合中的项目总数:https://marmelab.com/react-admin/DataProviders.html#usage
,- 在后端应用程序中添加 cors 中间件:
app.use(cors({
exposedHeaders: ['Content-Range']
}));
- 在响应头中包含 Content-Range:
const countries = [{id:1,name:"Bangladesh"},{id:2,name:"India"}];
return res
.status(200)
.set("Content-Range",countries.length)
.json(countries);
- 在你的 React 应用中
<Admin
dataProvider={simpleRestProvider('http://localhost:8000/api/v1')}
>
<Resource
name="countries"
options={{ label: 'Countries' }}
list={CountryList}
/>
</Admin>
一切正常。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。