【问题标题】:React-Admin JWT token in header标头中的 React-Admin JWT 令牌
【发布时间】:2020-06-09 21:11:34
【问题描述】:

我正在测试 React-Admin https://github.com/marmelab/react-admin 还有restful APIhttps://github.com/hagopj13/node-express-mongoose-boilerplate

我想列出数据库中的用户,但出现错误:

GET http://localhost:4000/v1/users?filter=%7B%7D&range=%5B0%2C24%5D&sort=%5B%22createdAt%22%2C%22desc%22%5D 401 (Unauthorized)

这里是数据提供者:

import { fetchUtils } from "react-admin";
import { stringify } from "query-string";

const apiUrl = "http://localhost:4000/v1";
const httpClient = fetchUtils.fetchJson;

export default {
  getList: (resource, params) => {
    console.log(params.pagination);
    console.log(params.sort);
    const { page, perPage } = params.pagination;
    const { field, order } = params.sort;
    const query = {
      sort: JSON.stringify([field, order]),
      range: JSON.stringify([(page - 1) * perPage, page * perPage - 1]),
      filter: JSON.stringify(params.filter)
    };
    const url = `${apiUrl}/${resource}?${stringify(query)}`;

    return httpClient(url).then(({ headers, json }) => ({
      data: json,
      total: parseInt(
        headers
          .get("content-range")
          .split("/")
          .pop(),
        10
      )
    }));
  },

  getOne: (resource, params) =>
    httpClient(`${apiUrl}/${resource}/${params.id}`).then(({ json }) => ({
      data: json
    })),

  getMany: (resource, params) => {
    const query = {
      filter: JSON.stringify({ id: params.ids })
    };
    const url = `${apiUrl}/${resource}?${stringify(query)}`;
    return httpClient(url).then(({ json }) => ({ data: json }));
  },

  getManyReference: (resource, params) => {
    const { page, perPage } = params.pagination;
    const { field, order } = params.sort;
    const query = {
      sort: JSON.stringify([field, order]),
      range: JSON.stringify([(page - 1) * perPage, page * perPage - 1]),
      filter: JSON.stringify({
        ...params.filter,
        [params.target]: params.id
      })
    };
    const url = `${apiUrl}/${resource}?${stringify(query)}`;

    return httpClient(url).then(({ headers, json }) => ({
      data: json,
      total: parseInt(
        headers
          .get("content-range")
          .split("/")
          .pop(),
        10
      )
    }));
  },

  update: (resource, params) =>
    httpClient(`${apiUrl}/${resource}/${params.id}`, {
      method: "PUT",
      body: JSON.stringify(params.data)
    }).then(({ json }) => ({ data: json })),

  updateMany: (resource, params) => {
    const query = {
      filter: JSON.stringify({ id: params.ids })
    };
    return httpClient(`${apiUrl}/${resource}?${stringify(query)}`, {
      method: "PUT",
      body: JSON.stringify(params.data)
    }).then(({ json }) => ({ data: json }));
  },

  create: (resource, params) =>
    httpClient(`${apiUrl}/${resource}`, {
      method: "POST",
      body: JSON.stringify(params.data)
    }).then(({ json }) => ({
      data: { ...params.data, id: json.id }
    })),

  delete: (resource, params) =>
    httpClient(`${apiUrl}/${resource}/${params.id}`, {
      method: "DELETE"
    }).then(({ json }) => ({ data: json })),

  deleteMany: (resource, params) => {
    const query = {
      filter: JSON.stringify({ id: params.ids })
    };
    return httpClient(`${apiUrl}/${resource}?${stringify(query)}`, {
      method: "DELETE",
      body: JSON.stringify(params.data)
    }).then(({ json }) => ({ data: json }));
  }
};

对于getList,如何在header中添加token进行授权?

更新:

dataProvider.js

getList: (resource, params) => {
    /*
    console.log(params.pagination);
    console.log(params.sort);
    const {
      page,
      perPage
    } = params.pagination;
    const {
      field,
      order
    } = params.sort;
    */
    const query = {
      /*
      sort: JSON.stringify([field, order]),
      range: JSON.stringify([(page - 1) * perPage, page * perPage - 1]),
      filter: JSON.stringify(params.filter)
      */
    };
    const url = `${apiUrl}/${resource}/${stringify(query)}`;
    const token = localStorage.getItem('token');
    return httpClient(url).then(({
        headers: {
          "authorization": token
        }
      }, json
    }) => ({
      data: json,
      total: parseInt(
        headers
        .get("content-range")
        .split("/")
        .pop(),
        10
      )
    }));
  },

但我得到这个错误:

./src/middlewares/dataProvider.js
  Line 35:5:  Parsing error: Unexpected token, expected ","

  33 |         }
  34 |       }, json
> 35 |     }) => ({
     |     ^
  36 |       data: json,
  37 |       total: parseInt(
  38 |         headers

感谢和问候

卢多

【问题讨论】:

  • 括号打错了,把}换成)
  • 如果我替换为 ) 我有这个错误:./src/middlewares/dataProvider.js Line 27:6: Parsing error: Unexpected token, expected ";" 25 | } 26 | }, json > 27 | )) => ({ | ^ 28 | data: json, 29 | total: parseInt( 30 | headers
  • 尝试把括号 } 完全去掉,没必要!
  • 我删除了不必要的 } ,我得到一个不同的错误:Failed to compile ./src/middlewares/dataProvider.js Line 24:11: 'headers' is not defined no-undef
  • 在浏览器调试器中查看你的网络请求,检查其格式是否符合要求:“Include the JWT in requests”:passportjs.org/packages/passport-jwt

标签: reactjs jwt authorization token react-admin


【解决方案1】:

您必须在 DataProvider 中更改您的 httpClient,因此每个方法都将使用正确的凭据。

改变这个:

const httpClient = fetchUtils.fetchJson;

到这里:

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

来源:https://marmelab.com/react-admin/Authentication.html

【讨论】:

    【解决方案2】:

    添加一个 const const token = localStorage.getItem('token'); 并按如下方式使用

    getList: (resource, params) => {
      console.log(params.pagination);
      console.log(params.sort);
      const {
        page,
        perPage
      } = params.pagination;
      const {
        field,
        order
      } = params.sort;
      const query = {
        sort: JSON.stringify([field, order]),
        range: JSON.stringify([(page - 1) * perPage, page * perPage - 1]),
        filter: JSON.stringify(params.filter)
      };
      const url = `${apiUrl}/${resource}?${stringify(query)}`;
      const token = localStorage.getItem('token');
      return httpClient(url).then(({
          headers: {
            "authorization": token
          }
        }, json
      }) => ({
        data: json,
        total: parseInt(
          headers
          .get("content-range")
          .split("/")
          .pop(),
          10
        )
      }));
    },

    您也可以对其他请求执行相同操作。

    【讨论】:

    • 谢谢,我有一个错误`编译失败。 ./src/middlewares/dataProvider.js 第 31:5 行:解析错误:意外令牌,预期“,” 29 | } 30 | }, json > 31 | }) => ({ | ^ 32 | data: json, 33 | total: parseInt( 34 | headers `
    猜你喜欢
    • 2022-01-20
    • 1970-01-01
    • 2019-08-19
    • 2022-11-10
    • 2020-05-27
    • 2014-09-02
    • 2016-03-08
    • 2017-02-07
    相关资源
    最近更新 更多