node.js - 将 MERN 应用程序部署到 Azure 中,一直使用 "localhost"在本地运行

标签 node.js azure azure-web-app-service mern

我正在使用 MERN 堆栈和 MongoDB 开发一个 Web 应用程序,但在将该应用程序部署到 Azure Web 服务时遇到问题。到目前为止,我已经能够在 localhost 上正常运行该应用程序,但我不确定为什么我的应用程序无法在 Azure 环境中运行。

来自 server.js 的片段

app.use(express.json({extended: false}));
app.use(cors());
const URI = "db_URI";

mongoose.connect(URI, { 
        useUnifiedTopology: true, 
        useNewUrlParser: true,
        useCreateIndex: true
    });
connection = mongoose.connection;
connection.once('open', () => {
    console.log('db connected..!');
});

app.get("*", (req, res) => {
    res.sendFile(path.resolve(__dirname, "client", "build",     
    "index.html"));
 });
 
app.use('/api/userModel', require('./backend/routes/User'));
app.use('/projects', require('./backend/routes/projects'));
const Port = process.env.Port || 2000;
app.set('port', Port)
app.listen(Port,()=>console.log("Server started on port " + Port));

连接使用

axios.get('http://localhost:2000/projects/' + this.props.match.params.id)

我必须如何更改此连接才能在 Azure 中工作?

最佳答案

无需更改您的连接使用情况。

server.js 上使用 express.static 中间件允许服务器从指定目录提供静态资源。

const express = require('express');
const path = require("path"); // on top

// Serve Static assests if in production
if (process.env.NODE_ENV === "production") {
  app.use(express.static("client/build")); // change this if your dir structure is different
  app.get("*", (req, res) => {
    res.sendFile(path.resolve(__dirname, "client", "build", "index.html"));
  });
}

请看看这些:

  1. Creating MERN Stack App and Hosting In Microsoft Azure
  2. How to Deploy a MERN Stack App to Azure via Continuous Integration
  3. A way to deploy a MERN app to Azure instead of Heroku

关于node.js - 将 MERN 应用程序部署到 Azure 中,一直使用 "localhost"在本地运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66961139/

相关文章:

Azure网站: How to manually import application settings from a file

javascript - 测试服务时没有调用 NestJS UseFilter

azure - 如何升级 Azure ACS 集群

node.js - 如何使用soap和nodejs向chronopost发出运输请求

python - 使用 python azure-devops 包时,如何使用 PAT 进行身份验证?

azure - Azure DevOps 中的缓存

Azure Web 部署任务失败 - 存在未闭合的文字字符串

azure - 如何控制 Azure 诊断日志的日志级别?

node.js - 用 mongoose 对 alpha 进行排序

node.js - 使用 Update with Upsert 为 true 时未设置默认值