【问题标题】:NodeJS Express API only returns index.html file on production?NodeJS Express API 仅在生产时返回 index.html 文件?
【发布时间】:2020-10-05 14:13:18
【问题描述】:

我原来的问题:How to set up VueJS routes and NodeJS Express API routes?

我收到反馈,如果Serving VueJS Builds via Express.js using history mode 问题不能解决我的问题,我需要提出一个新问题,所以我来了。

问题:
NodeJS(由 express 提供支持)API 始终返回 index.html - 无论如何。

备注
- 在本地效果很好
- API 仅在生产环境中返回 index.html 文件

我很困惑这是什么原因造成的?

我也将我的 Nginx 配置放在这里,因为我认为它与我的生产服务器有关,因为问题只发生在那里:

server {
    root /var/www/example.com/client/dist;
    index index.html index.htm index.nginx-debian.html;

    server_name example.com www.example.com;

    location / {
        try_files $uri $uri/ /index.html;

        proxy_pass http://localhost:1234;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection 'upgrade';
        proxy_set_header Host $host;
        proxy_cache_bypass $http_upgrade;
    }
}

NodeJS 服务器:

// server.js
const express = require("express");
const app = express();
const history = require("connect-history-api-fallback");
const cors = require("cors");
const bodyParser = require("body-parser");
const path = require("path");
const http = require("http");
const server = http.createServer(app);

app.use(cors());
app.use(
  bodyParser.urlencoded({
    extended: true,
  })
);
app.use(bodyParser.json());

app.get(`/user`, async (req, res){
  // Also, I have tested with res.json AND setting the content type manually
  return res.send({ test: 123 });
});

app.use(history());
app.use(express.static(path.join(__dirname, "../client/dist")));
app.get(`/`, (req, res) => {
  res.sendFile(path.join(__dirname, "../client/dist", "index.html"));
});

server.listen(1234);

问题:
NodeJS(由 express 提供支持)API 始终返回 index.html - 无论如何。

【问题讨论】:

    标签: javascript node.js express


    【解决方案1】:

    我最终将所有 API 端点放在 /api 前缀下,并将 Nginx 配置更改为如下所示:

    location / {
        try_files $uri $uri/ /index.html;
    
        location /api {
            proxy_pass http://localhost:1234;
            proxy_http_version 1.1;
            proxy_set_header Upgrade $http_upgrade;
            proxy_set_header Connection 'upgrade';
            proxy_set_header Host $host;
            proxy_cache_bypass $http_upgrade;
        }
    }
    

    所以,现在使用 /api/user 而不是 /user 可以按预期工作。不再返回 index.html 文件。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-06-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-03-15
      • 2021-01-23
      • 2020-09-16
      • 1970-01-01
      相关资源
      最近更新 更多