问题
My original question: How to set up VueJS routes and NodeJS Express API routes?
I got feedback that if Serving VueJS Builds via Express.js using history mode question doesn't solve my issue, I need to ask a new question, so here I'm.
Problem:
NodeJS (powered by express) API return always index.html
- no matter what.
Notes
- Works great on local
- API returns the index.html
file only on production
I'm super confused what can cause this?
I place my Nginx configs in here as well, since I think it has something to do my production server since the issue only happens there:
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;
}
}
NodeJS server:
// 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());
app.get(`/user`, async (req, res){
// Also, I have tested with res.json AND setting the content type manually
return res.send({ test: 123 });
});
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"));
});
server.listen(1234);
Problem:
NodeJS (powered by express) API return always index.html
- no matter what.
回答1:
I ended up placing all API
endpoints under /api
prefix and changed the Nginx configs to be something like this:
location / {
try_files $uri $uri/ /index.html;
location /api {
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;
}
}
So, now using /api/user
instead of /user
works as expected. Doesn't return the index.html
file anymore.
来源:https://stackoverflow.com/questions/62400547/nodejs-express-api-only-returns-index-html-file-on-production