【问题标题】:How to set up VueJS routes and NodeJS Express API routes? [duplicate]如何设置 VueJS 路由和 NodeJS Express API 路由? [复制]
【发布时间】:2020-10-05 02:02:48
【问题描述】:

API 路由总是返回 HTML 从不 JSON - 我尝试了很多不同的解决方案,但都没有奏效。

这是当前的设置:

// 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());

require("./routes")(app);

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"));
});



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

问题:
无论如何,点击/user 端点将始终返回index.html 文件。

我错过了什么?

顺便说一句,在本地效果很好,而不是在生产上。可能与 Nginx 配置有关吗?

// Nginx configs

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;
    }
}

【问题讨论】:

  • 通过删除 SPA 的路由,API 端点会抛出 Cannot GET /index.html
  • 如果有人有同样的问题,你可以阅读我的解决方案我发布到我的另一个问题:stackoverflow.com/questions/62400547/…

标签: javascript node.js express vue.js


【解决方案1】:

像 VueJS 这样的单页网站在客户端处理所有页面。 index.html 包含您需要在 vuejs 路由器中配置的所有页面。显示的页面取决于地址栏中的 url。

要修复您的代码,所有请求都应从dist返回一个静态文件(如果它存在),并且对于所有其他请求返回index.html。

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

【讨论】:

  • 提供文件没有问题,但访问了API 端点。 API 不应返回 index.html 文件
  • 如果有人有同样的问题,你可以阅读我的解决方案我发布到我的另一个问题:stackoverflow.com/questions/62400547/…
猜你喜欢
  • 2017-11-23
  • 2020-11-30
  • 2014-10-03
  • 1970-01-01
  • 1970-01-01
  • 2013-05-24
  • 1970-01-01
  • 2021-10-19
相关资源
最近更新 更多