简体   繁体   English

使用 Axios 在 Next.js 应用程序中调用外部 API

[英]Calling an external API within Next.js app with Axios

I want to fetch data from API and present it in the page.我想从 API 中获取数据并将其呈现在页面中。 I have an API routes in my app.我的应用程序中有一条 API 路线。

Inside of api/apps/get-apps.js I have:在 api/apps/get-apps.js 我有:

import { APPS_PATH, BASE_URL } from '../constants/api.constants';
import axios from 'axios';

export default async function handler(request, response) {
  const requestUrl = encodeURI(BASE_URL + APPS_PATH);    
  try {
    const axiosResponse = await axios.get(requestUrl);
    return response.status(200).send(axiosResponse.data);
  } catch (error) {
    return response.status(404).send('error');
  }
}

Inside pages/apps/index.js:内页/应用程序/index.js:

async function fetchAllReviews(id, callback) {
  try {
    const response = await axios.get('/api/reviews/get-apps');
    if (response.status === 200) {
      callback(true, response.data);
    }
  } catch (error) {
    callback(false, error);
  }

I want to add a query to the request with the id of the app, for instance:我想使用应用程序的 id 向请求添加查询,例如:

api/reviews/get-apps?id=248294829

And use it inside the handler for call to the outer API.并在handler中使用它来调用外部 API。


I tried to add: params: { id } object to the request, but inside get-apps.js , I don't get the params inside of the response.我尝试在请求中添加: params: { id } object ,但是在get-apps.js中,我没有得到响应中的参数。

// pages/apps/index.js

async function fetchAllReviews(id, callback) {
  const id = 'some-id';

  try {
    const response = await axios.get(`/api/reviews/get-apps?id=${id}`);
    if (response.status === 200) {
      callback(true, response.data);
    }
  } catch (error) {
    callback(false, error);
  }
}

You can access the id in the API handler as follows:您可以访问 API 处理程序中的id ,如下所示:

// api/apps/get-apps.js 

export default async function handler(request, response) {
  const { id } = request.query;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM