我正在使用 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"));
});
}
请看看这些:
关于node.js - 将 MERN 应用程序部署到 Azure 中,一直使用 "localhost"在本地运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66961139/