Help us understand the problem. What is going on with this article?

【Vue.js + express】本番環境のルーティングを設定する。

More than 1 year has passed since last update.

前提

rootパスのルーティングは設定済。

server.js
const express = require('express');
const port = process.env.PORT || 8080;
const app = express();
app.use(express.static(__dirname + "/dist/"));
app.listen(port);

目的

本番環境のrootパス以外のルーティングを設定する。

エラー確認

$ node server.js し、http://localhost:8080/hoge にアクセス。

エラー内容

Cannot GET /hoge
_.png

解決

server.jsファイル内を変更

▼ 変更前

server.js
const express = require('express');
const port = process.env.PORT || 8080;
const app = express();
app.use(express.static(__dirname + "/dist/"));
app.listen(port);

▼ 変更後

server.js
const express = require("express");
const port = process.env.PORT || 8080;
const app = express();

app.use(express.static(__dirname + "/dist/"));
app.get(/.*/, function(req, res) {
  res.sendfile(__dirname + "/dist/index.html");
});
app.listen(port);

console.log("Server started...");

参考

https://www.youtube.com/watch?v=yfW9knTBR90
https://github.com/jordanhudgens/vue-cli-three-heroku-template/blob/master/server.js

Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away