2017-06-03 81 views
0

我将express用作next.js的自定义服务器。一切都很好,当我点击的产品,以产品Next.js - 错误:仅支持绝对URL支持

步骤1名单:我点击产品链接

enter image description here

步骤2:它会显示在数据库中的产品。

enter image description here

但是如果我刷新/products一页,我会得到这个错误

enter image description here

Server代码(请看/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 

回答

4

由于错误状态,您将不得不使用您正在制作的fetch的绝对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 
    } 
} 
+0

谢谢,它 在工作,在忙! – sinusGob