【问题标题】:MEAN app in production: cannot call backend API生产中的平均应用程序:无法调用后端 API
【发布时间】:2019-07-09 19:15:03
【问题描述】:

我正在尝试部署我的 MEAN 应用。在 heroku 或其他地方这样做之前,我正在测试生产模式。当我在两个不同的端口上分别启动 Node 和 Angular 时,一切都在“开发模式”下工作。在生产模式下,我无法访问后端 API。

使用环境变量(见下文)我有 Node.js/Express 服务器在 /dist 中的 Angular 编译代码。以下是 Node.js 代码的一些相关摘录:

const express = require("express");
const path = require('path')
const cors = require('cors');
const  mongoose = require('mongoose');

const app = express();
... //some non-relevant stuff eg passport, body-parser ...

//Load configurations
const config = require('./config/config.js');
// Load routes
const storeroutes = require('./routes/stores.routes.js');
//Use mongoose to connect to the stores DB in mongoDB

mongoose.connect(config.mongoDB, { useNewUrlParser: true });
mongoose.connection.once('open', () => {
    console.log('Connection to the MongoDB database established successfully!');
});
// CORS Middleware
app.use(cors());
...
// Static Folders (used by Node)
app.use(express.static(path.join(__dirname, 'views')));
app.use(express.static(path.join(__dirname, 'public')));

// Serve Angular
if (process.env.NODE_ENV == 'production') {
  app.use(express.static("../dist/"));
  app.use((req, res) => {
    res.sendFile(path.join(__dirname, '../dist/index.html')); 
  });
}

// Use routes
app.use('/', storeroutes)

app.listen(config.port);

config/config.js 只是导出环境变量。所以请相信我 NODE_ENV='production'、config.port=4000 以及其他我没有显示的内容。

stores.routes.js 中的路由基本上是一个快速路由,正如我所说,一切都在开发模式下工作。例如,在开发模式下,http://localhost:4000/stores 的 API 显示在 mongoDB 数据库中

当我启动 NODE_ENV=production node server.js 时,前端页面显示正确,但在后台调用服务器 API 失败,请参阅屏幕截图。事实上,我无法导航到上面的 API 链接。

在我的 Angular 服务中,我按如下方式调用 API:

export class StoreService {
  uri:string = environment.node_url; //this is 'http://localhost:4000'
  // Fetches all documents.
  getAllStores() {
    return this.http.get(`${this.uri}/stores`);
  }
  ...
}

我怀疑问题出在 Node/Express 代码 app.use((req, res) => { res.sendFile(.. 中,但可能是我在 Angular 中使用的 API 的 URL 中的问题(我应该尝试以某种方式使用 baseUrl 吗?)。

【问题讨论】:

    标签: node.js angular routing mean-stack


    【解决方案1】:

    下面的代码强制所有路由到前端的index.html:

    app.use((req, res) => {
      res.sendFile(path.join(__dirname, '../dist/index.html')); 
    });
    

    我首先通过删除这些行使其工作。 但是,更好的解决方案是将后端 API 置于之上,如下所示:

    // Use routes for backend API
    app.use('/', storeroutes)
    
    // Serve Angular
    if (process.env.NODE_ENV == 'production') {
      app.use(express.static("../dist/"));
      // Any request that is not the storeroutes above goes to Angular client
      app.get('*', (req, res) => {
        res.sendFile(path.resolve(__dirname, '../dist','index.html')); 
      });
    }
    

    【讨论】:

      猜你喜欢
      • 2013-12-15
      • 2018-04-15
      • 1970-01-01
      • 2021-06-25
      • 2010-09-27
      • 1970-01-01
      • 2017-05-24
      • 2018-09-01
      • 2022-12-07
      相关资源
      最近更新 更多