Next.js - Error: only absolute urls are supported

后端 未结 6 1121
感动是毒
感动是毒 2020-12-29 10:05

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 produc

相关标签:
6条回答
  • 2020-12-29 10:11

    It looks like there's something wrong with the URL in the fetch method. For me, it solved by changing url in the fetch method. Pay attention to the correctness of the URL address.

    0 讨论(0)
  • 2020-12-29 10:16

    use .log(console.log) after nock , so you will get exact unmatched and expected url . Example:

         nock("http://localhost")
    .log(console.log)
    .persist()
    .get("/api/config")
    .reply(200, { data: 1234 })
    
    0 讨论(0)
  • 2020-12-29 10:17

    This simple solution worked for me without having to add an additional config file,

    Install

    npm install --save next-absolute-url
    

    Usage

    import absoluteUrl from "next-absolute-url";
    
    async getInitialProps({ req }){
      const { origin } = absoluteUrl(req, req.headers.host);
      console.log('Requested URL ->',origin); 
      // (or) other way
      const host = absoluteUrl(req, req.headers.host);
      console.log('Requested URL ->',host.origin); 
    }
    
    0 讨论(0)
  • 2020-12-29 10:18

    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
      }
    }
    
    0 讨论(0)
  • 2020-12-29 10:29

    In the NextJS 9.5, we can also use process.cwd().
    process.cwd() will give you the directory where Next.js is being executed.

    import path from 'path'
    import fs from "fs";
    
    export const getStaticProps: GetStaticProps = async () => {
        const dataFilePath = path.join(process.cwd(), "jsonFiles", "data.json");
        console.log(dataFilePath);     // will be YourProject/jsonFiles/data.json
    
        const fileContents = fs.readFileSync(dataFilePath, "utf8");
        const data: TypeOfData[] = JSON.parse(fileContents);
        return { props: { data } };
    };
    

    Ref: https://nextjs.org/docs/basic-features/data-fetching#reading-files-use-processcwd

    0 讨论(0)
  • 2020-12-29 10:33

    Case 1. It's not an error. The isomorphic-unfetch is running by SSR mode, so Node.js needs to know the absolute url to fetch from it, because the back-end doesn't know your browser settings.

    Case 2. Another scenario is to prevent the http host poisoning headers attack.

    append secret keys and tokens to links containing it:

    <a href="http://_SERVER['HOST']?token=topsecret">  (Django, Gallery, others)
    

    ....and even directly import scripts from it:

    <script src="http://_SERVER['HOST']/misc/jquery.js?v=1.4.4">
    

    Case 3. The isomorphic-unfetch it's the library we are going to use to fetch data. It's a simple implementation of the browser fetch API, but works both in client and server environments.

    Read more about it:

    1. Isomorphic unfetch - Switches between unfetch & node-fetch for client & server
    2. Prevent http host headers attack
    3. Fetching Data for Pages
    0 讨论(0)
提交回复
热议问题