【问题标题】:Is there a way to fetch without entering the server address有没有不输入服务器地址就可以获取的方法
【发布时间】:2021-04-22 09:03:48
【问题描述】:

这可能是一个非常愚蠢的问题,但有没有办法在不输入服务器地址的情况下获取?我想知道我是否可以只使用“/init”而不是“http://localhost:3000/init”

try{
    const result = await fetch("http://localhost:3001/init",
    {
      method:"GET",
      headers:{
        "content-type":"application/json"
      }
    });
    response = await result.json();
    }
  catch(e){
    console.log(e);
  }

【问题讨论】:

    标签: node.js api server fetch


    【解决方案1】:

    有没有办法不用输入服务器地址就可以获取

    没有。

    在 node.js 中,node-fetch 需要一个完全限定的 URL。没有“默认”目标域或路径可以替代,就像浏览器网页中的浏览器版本为 fetch() 一样。

    从节点获取documentation

    fetch(url[, options])
    
    url should be an absolute url, such as https://example.com/. 
    A path-relative URL (/file/under/root) or protocol-relative URL 
    (//can-be-http-or-https.com/) will result in a rejected Promise.
    

    如果您在这里真正要解决的问题是能够编写适用于不同主机的代码(在本地和托管环境中运行),那么您可以使用主机名设置某种配置变量,然后然后使用配置变量中的主机名构造您的 URL。

    【讨论】:

      猜你喜欢
      • 2015-04-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-11-25
      • 2020-06-05
      • 2012-09-11
      相关资源
      最近更新 更多