即使服务器正在发送数据

时间:2017-09-13 19:14:10

标签: javascript reactjs admin-on-rest

我正在尝试使用标头中的标记执行休息调用以显示信息。有一个必需的标头令牌,所以我的代码看起来像我的restClient.js,app.js和users.js。

//restClient.js
import { jsonServerRestClient, fetchUtils } from 'admin-on-rest';

const httpClient = (url, options = {}) => {
    if (!options.headers) {
        options.headers = new Headers({ Accept: 'application/json' });
    }
    options.headers.set('token', 'admin');
    return fetchUtils.fetchJson(url, options);
}

const restClient = jsonServerRestClient('http://localhost:8080/api/v2', httpClient);

export default (type, resource, params) => new Promise(resolve => setTimeout(() => resolve(restClient(type, resource, params)), 500));

//App.js
import React, {Component} from 'react';
import { Admin, Resource } from 'admin-on-rest';

import { UserList } from './users';
import restClient from './restClient';

class App extends Component {
  render() {
    return(
          <Admin restClient={restClient}>
              <Resource name="admin/user" list={UserList}/>
          </Admin>
    );
  }
}
export default App;

//Users.js
// in src/users.js
import React from 'react';
import { List, Datagrid, EmailField, TextField, SimpleList } from 'admin-on-rest';

export const UserList = (props) => (
    <List {...props}>
        <Datagrid >
            <TextField source="email"/>
            <TextField source="info"/>
        </Datagrid>
    </List>
);

Example of JSON

我已经用邮递员测试了我的休息电话,它肯定会返回数据。无论如何还要检查通话中发回的数据是什么?服务器正在运行express.js,我已经设置了包含所需头文件的路由。我还附上了一个我正在返回的JSON的示例。

2 个答案:

答案 0 :(得分:1)

因为aor fetchUtils返回一个promise。你可以拦截承诺并进行任何你想要的检查(并做更多的事情)

以下是我的代码处理类似内容的方式。我也拦截API调用并显示自定义通知。

function handleRequestAndResponse(url, options={}) {
  return fetchUtils.fetchJson(url, options)
    .then((response) => {
      const {headers, json} = response;
      //admin on rest needs the {data} key
      const data = {data: json}
      if (headers.get('x-total-count')) {
        data.total = parseInt(headers.get('x-total-count').split('/').pop(), 10)
      }
      // handle get_list responses
      if (!isNaN(parseInt(headers.get('x-total-count'), 10))) {
        return {data: json,
                total: parseInt(headers.get('x-total-count').split('/').pop(), 10)}
      } else {
        return data
      }
  })
}

您可以简单地执行以下操作

return fetchUtils.fetchJson(url, options)
.then(res => {
    console.log(res)
    return res
})

答案 1 :(得分:0)

我没有评论的声誉,但Fiddler 4是查看用户界面发送到服务器的好方法。