问题描述
预期
如何在Axios请求中将键和值作为标题放置。
动作
我有这个API端点https://netsocial-129849.uc.r.appspot.com/api/v1/posts
要获得响应,我需要传递值为key
的{{1}}和值为Authorization
的{{1}}
在我的移动应用中,我使用 Axios 请求
value
5wrA97fGbbDCepQXf6qzyz9B6SzjK0YZXIg8kSQrPc8lEnUBAIXl1fg5ez08DfdU32T4B8anxDykG6joAIorPqM8vG
使用React Native的客户端
export default axios.create({
baseURL: 'https://netsocial-129849.uc.r.appspot.com/api/v1/posts',headers: {
Authorization: 'Bearer 5wrA97fGbbDCepQXf6qzyz9B6SzjK0YZXIg8kSQrPc8lEnUBAIXl1fg5ez08DfdU32T4B8anxDykG6joAIorPqM8vG',}
});
解决方法
完成axios请求的方式没有错误。 您只需要像使用它一样使用promise-
axios.create({
baseURL: 'https://netsocial-129849.uc.r.appspot.com/api/v1/posts',headers: {
Authorization: 'Bearer 5wrA97fGbbDCepQXf6qzyz9B6SzjK0YZXIg8kSQrPc8lEnUBAIXl1fg5ez08DfdU32T4B8anxDykG6joAIorPqM8vG',}
})
.then((data) => {
console.log(data);
}).catch((error)=>{
console.log("Error");
});
,
您能尝试使用useEffect
钩子来进行API调用吗?
import React,{useEffect} from "react";
..
..
const NetSocialApi = () => {
const [results,setResults] = useState([]);
const searchApi = async() => {
const response = await netsocial.get('/');
setResults(response.data);
}
useEffect(()=>{
searchApi();
},[])
return (
<View>
<Text>{results}</Text>
</View>
);
}