[英]React-Admin JWT token in header
我正在測試 React-Admin https://github.com/marmelab/react-admin和 restful API https://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進行授權?
更新:
數據提供者.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
感謝和問候
盧多
添加一個 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 ) })); },
您也可以對其他請求執行相同操作。
您必須在 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);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.