简体   繁体   English

404 Not Found Next.js React-Query 获取错误

[英]404 Not Found Next.js error on React-Query fetch

Here is my situation.这是我的情况。 I am trying to set up a Next.js project with an Express.js back-end.我正在尝试使用 Express.js 后端设置 Next.js 项目。 I did set up the back-end as a regular one not as a custom server according to Next.js documentation.根据 Next.js 文档,我确实将后端设置为常规服务器,而不是自定义服务器。 So I am not sure if I am already making a mistake by setting up the back-end as a regular one.因此,我不确定将后端设置为常规后端是否已经犯了错误。 I am trying to fetch data from a back-end endpoint http://localhost:3500/api/v1/list using axios and it works well.我正在尝试使用 axios 从后端端点http://localhost:3500/api/v1/list获取数据,并且效果很好。 But when I am trying to implement React-Query on the first load I am getting the right data from the back-end but when it is trying to re-fetch for some reason it is hitting the wrong end-point http://localhost:3600/api/v1/list and getting the 404 Not Found error.但是,当我尝试在第一次加载时实现 React-Query 时,我从后端获取了正确的数据,但是当它出于某种原因尝试重新获取时,它遇到了错误的端点http://localhost:3600/api/v1/list并得到 404 Not Found 错误。 It looks like it is switching the port from 3500 to 3600 which is a front-end port.看起来它正在将端口从3500切换到3600 ,这是一个前端端口。 Here you will find the link to the repository and here is the code.在这里,您将找到存储库的链接,这里是代码。 Let me know if I am doing something wrong,如果我做错了什么,请告诉我,

page/sell.js页面/sell.js

import axios from 'axios';
import { useQuery } from 'react-query';

export default function SellPage({ response }) {
  const { data, isLoading, error } = useQuery('sells', getPosts, {
    initialData: response,
  });

  console.log('data useQuery: ', data);

  if (isLoading) return 'Loading...';
  if (error) return error.message;
  return (
    <div>
      <p>Hello SellPage!!{data.message}</p>
    </div>
  );
}

export async function getServerSideProps(context) {
  const response = await getPosts();
  console.log('response', response);
  if (!response) {
    return {
      notFound: true,
    };
  }

  return {
    props: { response }, // will be passed to the page component as props
  };
}

async function getPosts() {
  console.log('HOST: ', process.env.HOST);
  const { data } = await axios.request({
    baseURL: process.env.HOST,
    url: '/api/v1/list',
    method: 'get',
  });
  return data;
}

_app.js _app.js

import React from 'react';
import { QueryClient, QueryClientProvider } from 'react-query';
import { ReactQueryDevtools } from 'react-query/devtools';

const queryClient = new QueryClient();

function MyApp({ Component, pageProps }) {
  const queryClientRef = React.useRef();
  if (!queryClientRef.current) {
    queryClientRef.current = new QueryClient();
  }
  return (
    <>
      <QueryClientProvider client={queryClientRef.current}>
        <Component {...pageProps} />
        <ReactQueryDevtools initialIsOpen={false} />
      </QueryClientProvider>
    </>
  );
}

export default MyApp;

I don't see a next.config.js in your repo, so I guess the env variables are not bundled in the js and in the end you url looks like localhost: or localhost:undefined which the browser default to the port your client is served.我在您的存储库中没有看到next.config.js ,所以我猜 env 变量没有捆绑在 js 中,最后您 url 看起来像localhost:localhost:undefined浏览器默认为您的客户端的端口送达。

Try add next.config.js尝试添加next.config.js

module.exports = {
  env: {
    HOST: process.env.HOST,
  },
}

SEE: https://nextjs.org/docs/api-reference/next.config.js/environment-variables参见: https://nextjs.org/docs/api-reference/next.config.js/environment-variables

Another way is to use public runtime variables另一种方法是使用公共运行时变量

module.exports = {
  publicRuntimeConfig: {
    // Will be available on both server and client
    port: 3500,
  },
};

// Then
import getConfig from 'next/config';

// Only holds serverRuntimeConfig and publicRuntimeConfig
const { publicRuntimeConfig } = getConfig();
console.log(publicRuntimeConfig.port);

SEE: https://nextjs.org/docs/api-reference/next.config.js/runtime-configuration参见: https://nextjs.org/docs/api-reference/next.config.js/runtime-configuration

But note that runtime config would impact optimization and you might get larger bundle in the end so you might want to try build time variables first.但请注意,运行时配置会影响优化,最终您可能会得到更大的包,因此您可能想先尝试构建时间变量。

if you get 404 i think that you reached out the server but no API's name matched so try to test the API first on postman or alike however if console.log('HOST: ', process.env.HOST);如果您收到 404,我认为您已访问服务器但没有匹配的 API 名称,因此请尝试首先在 postman 或类似设备上测试 API,但是如果console.log('HOST: ', process.env.HOST); prints http://localhost:3600 then do the following in your .env file try to rename PORT TO SERVER_PORT or whatever打印http://localhost:3600然后在.env文件中执行以下操作尝试将PORT重命名为SERVER_PORT或其他

HOSTNAME=localhost
SERVER_PORT=3500
HOST=http://$HOSTNAME:$SERVER_PORT

i'm not sure but maybe ur frontend serve bash hold PORT env val as 3600我不确定,但也许你的前端服务 bash 将PORT env val 保持为3600

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

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