0
1

More than 1 year has passed since last update.

Vite(Vue3) + Laravel(XAMPP環境)でセッションが消える(Authが機能しない)

Last updated at Posted at 2022-03-05

イントロダクション

フロントエンド(Vue.js)

Vite(Vue3)でサーバーを立ち上げる。 → http://localhost:3000

バックエンド(Laravel)

XAMPPで立ち上げる。 → http://hogehoge.localhost

フロントエンドからバックエンドへは、axiosを使用。

axios.get(`http://hogehoge.localhost/api/auth/logout`)
        .then((response) => {
          console.log(response);
          if (response.data.status === 200) {
            router.push("login");
            return;
          } else {
            alert(apiErrorMessage.value);
            return;
          }
        })
        .catch((error) => {
          console.log(error);
        });

→ ログイン認証後、別のAPIを実行するとSESSION情報が消えている、、、。

結論

リクエストのドメインが、
http://hogehoge.localhost
ではなく、
http://localhost:3000
になっているので(クロスドメイン)、Cookieが取得できない→LaravelのAuthが機能しない。

image.png

なので、リクエストのドメインを、
http://hogehoge.localhost
に変装させる必要があります。

そのために使うのがvue.config.jsのproxy。

vue.config.jsに以下の内容を追記しましょう。(「^/api」の部分はもし異なるなら適宜、変更してくださいね。)

module.exports = {
    //
    devServer: {
        proxy: {
            '^/api': {
                target: 'http://hogehoge.localhost',
                changeOrigin: true
            },
        }
    }
}

そして、axiosの記述を書き換えます。(「http://hogehoge.localhost」を削除)

axios.get(`/api/auth/logout`)
        .then((response) => {
          console.log(response);
          if (response.data.status === 200) {
            router.push("login");
            return;
          } else {
            alert(apiErrorMessage.value);
            return;
          }
        })
        .catch((error) => {
          console.log(error);
        });

最後に、Viteを再起動!
→リクエストのドメインが「http://hogehoge.localhost」として処理されて、無事、セッションが引き継がれるようになりました。

この記事で100人ぐらい助かってくれるといいね。

0
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
0
1