我正在使用express作为下一步的自定义服务器.js.当我点击产品列表时,一切都很好

Step 1:我点击产品链接

enter image description here

Step 2:它会在数据库中显示产品.

enter image description here

然而,如果我刷新/products页,我会得到这个错误

enter image description here

服务器代码(查看/products个端点)

app.prepare()
.then(() => {
  const server = express()

  // This is the endpoints for products
  server.get('/api/products', (req, res, next) => {
    // Im using Mongoose to return the data from the database
    Product.find({}, (err, products) => {
      res.send(products)
    })
  })

  server.get('*', (req, res) => {
    return handle(req, res)
  })

  server.listen(3000, (err) => {
    if (err) throw err
    console.log('> Ready on http://localhost:3000')
  })
})
.catch((ex) => {
  console.error(ex.stack)
  process.exit(1)
})

页面-产品.js(将循环产品json数据的简单布局)

import Layout from '../components/MyLayout.js'
import Link from 'next/link'
import fetch from 'isomorphic-unfetch'

const Products = (props) => (
  <Layout>
    <h1>List of Products</h1>
    <ul>
      { props.products.map((product) => (
        <li key={product._id}>{ product.title }</li>
      ))}
    </ul>
  </Layout>
)

Products.getInitialProps = async function() {

  const res = await fetch('/api/products')
  const data = await res.json()

  console.log(data)
  console.log(`Showed data fetched. Count ${data.length}`)

  return {
    products: data
  }
}

export default Products

推荐答案

正如错误所述,您必须为正在生成的fetch个URL使用绝对URL.我假设它与代码可以在其上执行的不同环境(客户机和服务器)有关.相对URL只是不明确&;在这种情况下足够可靠.

解决这个问题的一种方法是将服务器地址硬编码到您的fetch请求中,另一种方法是设置一个config模块来响应您的环境:

/config/index.js

const dev = process.env.NODE_ENV !== 'production';

export const server = dev ? 'http://localhost:3000' : 'https://your_deployment.server.com';

products.js

import { server } from '../config';

// ...

Products.getInitialProps = async function() {

  const res = await fetch(`${server}/api/products`)
  const data = await res.json()

  console.log(data)
  console.log(`Showed data fetched. Count ${data.length}`)

  return {
    products: data
  }
}

Reactjs相关问答推荐

如何在没有 node 模块的情况下利用外部Java脚本文件制作OWL carousel

为什么登录错误和密码在创建Reaction-Hook-Form后立即被删除?

React-chartjs-2:红色和绿色之间的差距

在React中使用if条件时如何更改Tailwind中元素的文本 colored颜色

Syncfusion:带有 TabItemsDirective 的选项卡组件不显示任何内容

使用新数据更新时,React 不更新具有过滤功能的深层嵌套对象数组中的变量状态

为什么我会收到此错误:无法在我的react 包上读取 null 的属性(读取useState)?

根据其中的值不同地react setState 更新状态

使用 react pro 侧边栏展开折叠菜单

单元测试 useLoaderData() react-router v6 加载器函数

将 ref 赋予功能组件以使用内部功能

导航到屏幕时,react 本机上下文状态变为未定义

调用 Jest 和服务方法的问题

如何使用 babel 将 SVG 转换为 React 组件?

如何跨微前端 React 应用管理状态管理?

从输入中获取数字时,react 计数器不会增加

交换键仍然引入了 fresh 的 DOM 元素

axios post方法中的请求失败,状态码为500错误

运行开发服务器时如何为 Vite 指定运行时目录

点击提交后自动添加#