[英]React-Admin JWT token in header
I'm testing React-Admin https://github.com/marmelab/react-admin and the restful API https://github.com/hagopj13/node-express-mongoose-boilerplate我正在测试 React-Admin https://github.com/marmelab/react-admin和 restful API https://github.com/hagopj13/node-express-mongoose-boilerplate
I want to list the users in database but i get the error:我想列出数据库中的用户,但出现错误:
GET http://localhost:4000/v1/users?filter=%7B%7D&range=%5B0%2C24%5D&sort=%5B%22createdAt%22%2C%22desc%22%5D 401 (Unauthorized)
Here the Dataprovider:这里是数据提供者:
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 }));
}
};
For the getList, how to add the token in the header for authorization?对于getList,如何在header中添加token进行授权?
Update:更新:
dataProvider.js数据提供者.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
)
}));
},
But i get this error:但我收到此错误:
./src/middlewares/dataProvider.js
Line 35:5: Parsing error: Unexpected token, expected ","
33 | }
34 | }, json
> 35 | }) => ({
| ^
36 | data: json,
37 | total: parseInt(
38 | headers
Thanks & Regards感谢和问候
Ludo卢多
Add a const const token = localStorage.getItem('token');
添加一个 const
const token = localStorage.getItem('token');
and use it in the following way并按以下方式使用它
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 ) })); },
You can do same for other requests too.您也可以对其他请求执行相同操作。
You have to change your httpClient in the DataProvider, so every method will use the correct credentials.您必须在 DataProvider 中更改 httpClient,因此每种方法都将使用正确的凭据。
Change this:改变这个:
const httpClient = fetchUtils.fetchJson;
To this:对此:
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);
}
Source: https://marmelab.com/react-admin/Authentication.html来源: https : //marmelab.com/react-admin/Authentication.html
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.