现在,在我的React-Native应用程序中,我有以下内容:
fetch('http://localhost/SOMETHING', {
method: 'GET',
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer '+this.state.authtoken
}
})
目标:让我的API知道正在进行呼叫的UID。我知道应该在authtoken中,但是不同的用户可以使用相同的authtoken。
我最初的想法是在每个URL的末尾添加一个?uid=${UID}
。但是,我有GET,POST,PATCH和它们自己的查询集
另一种想法是添加带有UID数据的标头值。
不管我选择什么,将这个值添加到每个FETCH都非常好,而无需做很多其他工作。
这可能吗?公开建议您的工作。
答案 0 :(得分:0)
不确定您是否愿意离开fetch
,但我们使用apisauce。
import { create } from 'apisauce';
const api = create({
baseURL: 'http://localhost',
headers: { 'Accept': 'application/json' },
});
api.addRequestTransform(request => {
if (accessToken) {
request.headers['Authorization'] = `bearer ${accessToken}`;
}
});
api.get('/SOMETHING');
修改
如果您希望将其保持在fetch
附近,则可以创建一个辅助函数。
let authToken = null;
export const setAuthToken = token => {
authToken = token;
};
export const fetch = (url, options) => {
if (!options) {
options = {};
}
if (!options.headers) {
options.headers = {};
}
if (authToken) {
options.headers['Authorization'] = `Bearer ${authToken}`;
}
return fetch(url, options);
};
您可能只会使用一次setAuthToken
函数。
import { setAuthToken } from '../api';
// e.g. after login
setAuthToken('token');
然后通常使用fetch
的地方:
import { fetch } from '../api';
fetch('http://localhost/SOMETHING');
我不会考虑为每次创建一个辅助函数和一个额外的import语句来获取很多“额外工作”。
答案 1 :(得分:0)
您可以构建包装函数以使用uid进行获取
function fetchWithUid(baseUrl, uid, authtoken, options) {
const { method, headers, body, ...rest } = options;
const fetchOptions = {
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer ' + authtoken,
...headers,
},
method,
...rest,
};
if (body) {
fetchOptions.body = JSON.stringify(body);
}
return fetch(`${baseUrl}?uid=${uid}`, fetchOptions);
}
像这样使用fetchWithUid
函数,fetchOptions只是模仿原始的fetch函数的选项。
const fetchOptions = {
method: 'POST',
body: {
hello: 'world',
},
};
fetchWithUid('http://localhost/SOMETHING', 123, 'abcd', fetchOptions);
答案 2 :(得分:-1)
如果可以的话,最好是切换到Axios(https://github.com/axios/axios)-在那做起来要容易得多。
但是,如果您需要使用访存,那么https://github.com/werk85/fetch-intercept是您的解决方案。
示例代码
fetchIntercept.register({
request: (url, config) => {
config.headers = {
"X-Custom-Header": true,
...config.headers
};
return [url, config];
}
});