javascript - 如何设置 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"));
});
推荐阅读
- python - 打印函数中的值列表,但也需要返回它
- java - WebLogic java.lang.OutOfMemoryError:Java 堆空间
- java - 访问HashMap中抽象类的子类
- fetch - 正文被服务器接收时变为空
- reactjs - 在 React 中添加身份验证以避免重新加载时重定向到主页的更好方法
- javascript - 如何在Javascript中放大和缩小div后保持滚动顶部相同的位置,角度10
- c# - Html Agility Pack 返回“请求中止:无法创建 SSL/TLS 安全通道”,但仅在此特定 url 上
- node.js - 如何使用MongoDB从任意两个时间点减去最新数据
- javascript - 反应表中的条件 disableSortBy
- python - 我如何检测一个字符在字符串中出现的连续次数,如果它达到某个值打印到命令