【问题标题】:Set the PORT NodeJs Heroku设置 PORT NodeJs Heroku
【发布时间】:2021-07-07 14:27:51
【问题描述】:

我在 Heroku 上创建了一个应用,并提取了我的 GitHub 存储库。

我的应用程序显示良好,但每次我有一个新版本时,我的后端端口都会改变。

这是我尝试设置的方法:

const PORT = process.env.PORT || 5000

const corsOptions = {
    origin: 'localhost',
    credentials: true,
    optionsSuccessStatus: 200
}
app.use(cors(corsOptions));

app.use(express.json());
app.use(express.urlencoded({
    extended: true
}))
app.use(cookieParser())

if (process.env.NODE_ENV === "production") {
    app.use(express.static('client/build'))
}

// routes
app.use('/api', routes)

//server 
app.listen(PORT, () => {
    console.log(`Listening on port ${process.env.PORT}`)
})

即使我只设置5000,我也有一个类似Listening on port 54435的端口

知道如何为我的后端设置一个固定端口吗?

我需要它,因为我的前端 (React) 的 axios 请求需要端口(显然)

【问题讨论】:

    标签: node.js heroku server axios mern


    【解决方案1】:

    将您的应用部署到 heroku 后,heroku 会为您提供一个链接,例如mynewapp.heroku.com.

    现在在你的前端(React)的axios请求中,替换所有的

    http://localhost:5000mynewapp.heroku.com

    这里不需要指定任何端口号。

    【讨论】:

      【解决方案2】:

      无法在 Heroku 上对端口进行硬编码:应用必须绑定到运行时提供的 PORT

      每个应用程序都可以部署在 Web Dyno 中,因此您可以使用 herokuapp.com URL 调用后端。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-11-28
        • 1970-01-01
        • 2023-03-24
        • 1970-01-01
        • 2020-07-17
        • 2021-11-20
        相关资源
        最近更新 更多