我对本地人反应还很新,所以请保持温柔。我在componentDidMount内部有一个双重提取请求,该请求可以按预期工作:
componentDidMount() {
const auth = new Buffer('username:HASHGOESHERE');
const token = auth.toString('base64');
const authHeader = 'Basic ' + token;
fetch('https://example.com/api-connect/get-token.php', {
method: 'POST',
headers: {
'Authorization': authHeader,
'Content-Type': 'application/json'
},
}).then((response) => response.json())
.then((responseText) => {
if (responseText.status.status === 'success'){
fetch('https://example.com/api-connect/send-request.php?action=get_faq', {
method: 'POST',
headers: {
'Authorization': 'Bearer ' + responseText.payload.access_token,
'Content-Type': 'application/json',
},
})
.then((response) => response.json())
.then((responseData) => {
this.setState({
isLoading: false,
faqs: responseData.payload.faqs,
});
})
}else{
alert('Something has gone wrong.');
}
})
}
每次需要在我的整个应用程序中进行提取请求时,我都必须使用get令牌提取请求。我想知道是否有一种方法可以设置获取令牌获取请求(也许在另一个文件中),这样我可以在需要时调用/导入它,然后以某种方式将其第二次获取传递给它,而不必编写所有获取信息以上的请求。
希望我的要求是有道理的-如果需要,我可以提供更多代码。
预先感谢
答案 0 :(得分:1)
尝试就在等待中
反应组件
async componentDidMount() {
const auth = new Buffer('username:HASHGOESHERE');
const token = auth.toString('base64');
const authHeader = 'Basic ' + token;
const tokenRequest = await getToken();
if (tokenRequest.status.status === 'success'){
const response2 = await fetch('https://example.com/api-connect/send-request.php?action=get_faq', {
method: 'POST',
headers: {
'Authorization': 'Bearer ' + tokenRequest.payload.access_token,
'Content-Type': 'application/json',
},
})
const responseData = await response2.json();
this.setState({
isLoading: false,
faqs: responseData.payload.faqs,
});
}else{
alert('Something has gone wrong.');
}
}
Somefile.js
export const getToken = async () => {
const response = await fetch('https://example.com/api-connect/get-token.php', {
method: 'POST',
headers: {
'Authorization': authHeader,
'Content-Type': 'application/json'
},
})
const responseText = await response.json();
return responseText
}
别忘了将“ Somefile.js”导入到react组件。