首页 > 解决方案 > 在javascript中使用node.js的process.env.PORT

问题描述

我在 Node.JS 中有这段代码

var express = require ('express');
var app = express();

var port = process.env.PORT;

app.listen(port, () => console.log(`Listo el puerto ${port}!!`));

在这种情况下,我知道它被分配了一个系统端口。但是在我的 Javascript 中,我尝试使用 Fetch 时有以下编码:

fetch('https://localhost/')
    .then(res => res.json())
    .then(json => console.log(json));

我的问题是,为了能够在我的 Javascript 文件中使用来自 Node.JS 的答案,我应该在我的端口中放什么?因为我需要一个随机分配我系统的人---->。

https://localhost/port???

谢谢。

标签: javascriptnode.jsfetch

解决方案


正如@ringo 所说,对“/path/to/data”之类的 url 的任何获取都将自动使用当前域:端口。

你免费得到这个!

指定域和端口实际上会降低您的应用程序的弹性,因为如果您更改托管应用程序的位置,则需要更新所有内容以解决此问题!

所以从你的例子中:

fetch('/') // we don't include the https protocol, the localhost domain, or the port.
  .then(res => res.json())
  .then(json => console.log(json));

推荐阅读