如何通过 axios 获取 json 数据以与代理反应?

时间:2021-05-24 07:27:16

标签: 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   │       {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

像这样的一些包,只是准备了nextreactaxios

   1   │ {
   2   │   "name": "app",
   3   │   "version": "1.0.0",
   4   │   "description": "",
   5   │   "main": "index.js",
   6   │   "scripts": {
   7   │     "dev": "next dev",
   8   │     "build": "next build",
   9   │     "start": "next start"
  10   │   },
  11   │   "author": "",
  12   │   "license": "",
  13   │   "dependencies": {
  14   │     "axios": "^0.21.1",
  15   │     "next": "^10.2.2",
  16   │     "react": "^17.0.2",
  17   │     "react-dom": "^17.0.2"
  18   │   }
  19   │ }

当启动应用程序并从浏览器访问它时,我收到此错误:

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 设置代理?

1 个答案:

答案 0 :(得分:1)

提供给 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)
)

更多信息见官方README

Related issue here