LoginSignup
2
1

More than 3 years have passed since last update.

Vue Routerでページを更新or直接アクセス→CannotGETの対処 。Node.js(Express)の例

Last updated at Posted at 2020-12-07

Vue Routerでページを更新すると

zukan画面にいるときに、ページをリロードすると

画面
スクリーンショット 2020-12-08 0.14.26.png

Console
スクリーンショット 2020-12-08 0.25.15.png

みたいになる。

SPAは常にindex.html一枚で処理をしている。

にもかかわらず、URLが見かけ上のzukanのPATHにアクセスしようとするため、エラーになる。

環境

version
Node.js v11.15.0
OS macOS Catalina v10.15.7
プロセッサ Intel Core i5

原因

historyを設定してURLから#を削除していると起こる。
ちなみにhistoryとは下で設定したやつ。

router.js
const router = new Router({
  mode: 'history',
  base: process.env.BASE_URL,
  //...略

対処

#を削除しつつ、問題を解決する方法は公式サイトに解説されている。

Node.js(Express)の場合

自分が作ったものがこれだったのでもう少し詳しく。

公式にもあるように、connect-history-api-fallbackを使うと良い。

install

npm install connect-history-api-fallback

server.jsの例

app.use(history())を追加する位置に注意。
app.use(serveStatic(__dirname + "/docs"))よりも後に書くと動作しなくなった。

server.js
const express = require('express')
const serveStatic = require('serve-static')
const history = require('connect-history-api-fallback') // 追加
const port = process.env.PORT || 5000

app = express()
app.use(history()) // 追加
app.use(serveStatic(__dirname + "/docs"))
app.listen(port)
console.log('server started '+ port)
2
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
1