2

我在使用 getServerSideProps 函数的 NEXT JS 中使用 fetch 时遇到问题。当我开始使用这个框架时,我可能做得不好。访问外部 API 的所有凭据都是正确的。当我在 React 中使用相同的参数进行获取时,它会给我带来信息,但是使用 Next JS 它会返回 400 - Bad Request。

我将所有参数放在下面的同一块代码中,以便于理解。我正在使用像“”这样的凭据参数来保护隐私。它们是正确的,它们没有问题。

注意:我相信我必须以错误的方式使用 getServerSideProps 函数。我不知道除了编写函数之外,我是否需要在 Next JS 上进行任何配置。换句话说,这里显示的是我到目前为止实际写的内容。该程序直接从 index.js 调用。

这是文件夹结构:

文件夹结构

ListOrders 是我呈现页面的地方。它从我执行提取的 getServerSideProps 函数接收 {orders} 作为道具。

const ListOrders = ({ orders }) => {
  // Render orders through server side rendering (SSR)
  return (
    <div>
      {/* If orders is an object than map over it to render the page, otherwise orders is an error message */}
      {typeof orders != "string" && orders.length > 0 ? (
        showOrders(orders)
      ) : (
        <h5>{orders}</h5>
      )}
    </div>
  );
};

const showOrders = (orders) => {
  {
    orders.list.map((o, i) => <h3 key={i}>{o.orderId}</h3>);
  }
};

export async function getServerSideProps() {
  // URL PARMS
  const accountName = "<conta>";
  const environment = "<ambiente usado>";
  const filter = "orders";

  // OPTIONS PARMS
  const accept = "application/json";
  const contentType = "application/json; charset=utf-8";

  // SET ACCESS CREDENTIALS
  const appKey = "<chave>";
  const appToken = "<token>";

  // DEFINE URL TO FETCH LIST ORDERS WITH FILTER PARMS
  const url = `https://${accountName}.${environment}.com.br/api/${filter}`;

  // DEFINE OPTIONS ACCORDING TO API

  const options = {
    method: "GET",
    headers: {
      Accept: accept,
      "Content-Type": contentType,
      "API-AppKey": appKey,
      "API-AppToken": appToken,
    },
  };

  // FETCH LIST ORDERS
  const res = await fetch(url, options);

  if (!res.ok) {
    //*! Fetch error: Client (400–499) or Server errors (500–599) (Return error message to the page)
    const qs_str = JSON.stringify(options.qs);
    const headers_str = JSON.stringify(options.headers);

    const statusDescription = setStatusDescription(res.status);

    const orders = `Error: ${res.status} ${statusDescription} ${url} ${options.method} - ${qs_str} - ${headers_str}`;
    return { props: { orders } };
  }

  const data = await res.json();

  if (!data) {
    //*?  Fetch not found (Return 404 to the page)
    return { notFound: true };
  }

  //* Fetch is OK and returning data as expected (Return object orders to the page)
  const orders = JSON.parse(JSON.stringify(data)); 
  return { props: { orders } };
}

即使我更改了 axios 的 fetch,我仍然有相同的 400 错误。我知道这听起来很可悲,但我想指出 fetch 本身没有任何问题。问题应该出在 NEXT JS 的工作方式上。

 // FETCH LIST ORDERS

  let orders;

  try {
    const response = await axios.get(url, options);
    //*? Fetch is OK and returning data as expected (Return object orders to the page)
    const ordersList = response.data;
    orders = JSON.parse(JSON.stringify(ordersList)); 
  } catch (error) {
    //*! Fetch error: Client (400–499) or Server errors (500–599) (Return error message to the page)
    const qs_str = JSON.stringify(options.qs);
    const headers_str = JSON.stringify(options.headers);
    orders = `Error 2: ${error} ${url} ${options.method} - ${qs_str} - ${headers_str}`;
  }
  return { props: { orders } };
}
4

0 回答 0