如何设置 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;
}
}

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

最新更新