**Home.jsx**
import { FetchDataFromApi } from "../../utils/api";
import { useEffect } from "react";
const Home = () => {
useEffect(()=>{
getCategory();
})
const getCategory = ()=>{
FetchDataFromApi("/api/categories/populate=*").then((res)=>{
console.log(res);
})
}
return (...)}
export default Home
------------------------------------------------------------------
**api.js**
import axios from "axios";
const params = {
headers:{
Authorization: "bearer " + "myApiToken"
}
}
export const FetchDataFromApi = async(url)=>{
try{
const {data} = await axios.get("http://localhost:1337" + url, params)
return data;
}catch (err){
console.log(err);
return err;
}
}
我正在尝试在 React 应用程序中使用 Axios 向 API 端点发出 GET 请求。当我在 URL 中包含查询参数“populate=*”时,我始终收到 404 Not Found 错误。但是,当我删除此参数时,请求工作正常,但随后我无法获取图像的详细信息。我正在关注的某人的代码虽然有效。
错误-“无法加载资源:服务器响应状态为404(未找到):1337/api/categories/populate=*”
查询参数由
?
符号分隔,而不是/
。所以你需要写下如下。
FetchDataFromApi("/api/categories?populate=*").then((res)=>{
console.log(res);
})
“如果你的请求有很多查询参数,你必须用
&
符号将它们连接起来。你可以在你的脑海中确定查询参数的顺序。
FetchDataFromApi("/api/categories?populate=*&city=abc&other=other").then((res)=>{
console.log(res);
})