Reactjs 如何在react with proxy中通过axios获取json数据?
我用next.js创建了一个应用程序。在其中一个页面中,编写了以下代码:Reactjs 如何在react with proxy中通过axios获取json数据?,reactjs,api,proxy,axios,next.js,Reactjs,Api,Proxy,Axios,Next.js,我用next.js创建了一个应用程序。在其中一个页面中,编写了以下代码: ../pages/index.js 1 │ import axios from 'axios'; 2 │ 3 │ const Page = ({ data }) => { 4 │ return ( 5 │ <div> 6 │ <div>Welcome to Next.js!</div> 7
../pages/index.js
1 │ import axios from 'axios';
2 │
3 │ const Page = ({ data }) => {
4 │ return (
5 │ <div>
6 │ <div>Welcome to Next.js!</div>
7 │ {data.map((d) => (
8 │ <p key={d.id}>{d.title}</p>
9 │ ))}
10 │ </div>
11 │ );
12 │ };
13 │
14 │ export const getStaticProps = async () => {
15 │ const { data } = await axios.get('http://localhost:4000/posts');
16 │ console.log(data);
17 │ return {
18 │ props: {
19 │ data,
20 │ },
21 │ };
22 │ };
23 │
24 │ export default Page
启动应用程序并从浏览器访问时,我遇到以下错误:
Server Error
Error: Request failed with status code 504
This error happened while generating the page. Any console logs will be displayed in the terminal window.
有时也会出现403错误
从应用程序的日志中,我发现了一些信息,如
app_1 | responseUrl:
app_1 | 'http://proxy.company.com:12302/http://localhost:4000/posts',
...
app_1 | isAxiosError: true,
app_1 | toJSON: [Function: toJSON]
为什么添加前缀
http://proxy.company.com:12302/
?如何使用axios设置代理?提供给axios HTTP函数的URL将从上下文附加到基本URL
您可以通过创建axios实例并将其用于HTTP调用来覆盖基本URL
const instance = axios.create({
baseURL: 'http://localhost:4000'
});
instance.get('/posts').then(
res => console.log(res, res.data),
err => console.log(err)
)
更多信息请访问官方网站
如何以这种方式返回
res
数据?您只需将console.log(res,res.data)
替换为res.data
。不带大括号的javascript arrow函数返回箭头后面的表达式。您还需要等待async axios调用将结果分配到变量中,如问题示例所示。
const instance = axios.create({
baseURL: 'http://localhost:4000'
});
instance.get('/posts').then(
res => console.log(res, res.data),
err => console.log(err)
)