如何设置VueJS路由和NodeJS Express API路由? [英] How to set up VueJS routes and NodeJS Express API routes?
问题描述
API路由始终返回 HTML
绝不返回 JSON
-我尝试了很多不同的解决方案,但没有一个起作用.
API routes return always HTML
never JSON
- I have tried a lot of different solutions but none of them worked.
这是当前设置:
// 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
文件,无论如何.
The problem:
Hitting /user
endpoint will always return the index.html
file, no matter what.
我缺少什么?
顺便说一句,在本地而不是在生产环境下效果很好.可以和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路由器中配置的所有页面.显示的页面取决于地址栏中的网址.
A one-page website like VueJS handles all the pages client-side. index.html
contains all the pages you need configured in your vuejs router. The page shown depends on the url in your address bar.
要修复您的代码,所有请求应从 dist
返回一个静态文件(如果存在),而对于所有其他请求,则返回 index.html
.
To fix your code all the request should return a static file from dist
if it exists and for all other requests return index.html
.
app.use(express.static(path.join(__dirname, "../client/dist")));
app.get((req, res) => {
res.sendFile(path.join(__dirname, "../client/dist", "index.html"));
});
这篇关于如何设置VueJS路由和NodeJS Express API路由?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!