首页 > 解决方案 > 如何设置 VueJS 路由和 NodeJS Express API 路由?

问题描述

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

标签: javascriptnode.jsexpressvue.js

解决方案


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

推荐阅读