Next.js - 错误:仅支持绝对网址 [英] Next.js - Error: only absolute urls are supported

查看:16
本文介绍了Next.js - 错误:仅支持绝对网址的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

第 1 步:我点击产品链接

第 2 步:它会显示数据库中的产品.

但是,如果我刷新 /products 页面,我会收到此错误

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

app.prepare().then(() => {const server = express()//这是产品的端点server.get('/api/products', (req, res, next) => {//我使用 Mongoose 从数据库中返回数据Product.find({}, (err, products) => {res.send(产品)})})server.get('*', (req, res) => {返回句柄(请求,资源)})server.listen(3000, (err) => {如果(错误)抛出错误console.log('>Ready on http://localhost:3000')})}).catch((ex) => {控制台错误(例如堆栈)process.exit(1)})

Pages - products.js(循环产品 json 数据的简单布局)

从'../components/MyLayout.js'导入布局从下一个/链接"导入链接从 'isomorphic-unfetch' 导入 fetchconst 产品 = (道具) =>(<布局><h1>商品一览</h1><ul>{ props.products.map((product) => (<li key={product._id}>{ product.title }</li>))}</布局>)Products.getInitialProps = 异步函数(){const res = await fetch('/api/products')const 数据 = 等待 res.json()控制台日志(数据)console.log(`显示的数据已获取.计数 ${data.length}`)返回 {产品:数据}}出口默认产品

解决方案

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

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

/config/index.js

const dev = process.env.NODE_ENV !== 'production';导出常量服务器 = 开发?'http://localhost:3000' : 'https://your_deployment.server.com';

products.js

import { server } from '../config';//...Products.getInitialProps = 异步函数(){const res = await fetch(`${server}/api/products`)const 数据 = 等待 res.json()控制台日志(数据)console.log(`显示的数据已获取.计数 ${data.length}`)返回 {产品:数据}}

I'm using express as my custom server for next.js. Everything is fine, when I click the products to the list of products

Step 1: I click the product Link

Step 2: It will show the products in the database.

However if I refresh the /products page, I will get this Error

Server code (Look at /products endpoint)

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)
})

Pages - products.js (Simple layout that will loop the products json data)

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

解决方案

As the error states, you will have to use an absolute URL for the fetch you're making. I'm assuming it has something to do with the different environments (client & server) on which your code can be executed. Relative URLs are just not explicit & reliable enough in this case.

One way to solve this would be to just hardcode the server address into your fetch request, another to set up a config module that reacts to your environment:

/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
  }
}

这篇关于Next.js - 错误:仅支持绝对网址的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆