问题
API routes return always HTML
never JSON
- I have tried a lot of different solutions but none of them worked.
Here is the current setup:
// 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 });
});
}
The problem:
Hitting /user
endpoint will always return the index.html
file, no matter what.
What I'm missing?
Btw, works great on local, not on production. Can be something to do with the Nginx config?
// 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;
}
}
回答1:
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.
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"));
});
来源:https://stackoverflow.com/questions/62391953/how-to-set-up-vuejs-routes-and-nodejs-express-api-routes