3
VueJSをフロントエンドとして使用し、Laravelをバックエンドとして使用してシングルページアプリケーション(SPA)を構築しようとしています。
私は問題などの認証トークンを管理するために
Laravel API - ページをリロードした直後に認証が行われる
をlaravel's passportを使用しています:ログイン後、私は正常に認証されるようにページをリロードする必要があります。
ログイン方法
data() {
return {
email: '',
password: '',
}
},
methods: {
login() {
var data = {
client_id: 2,
client_secret: '****************************',
grant_type: 'password',
username: this.email,
password: this.password
}
// send data
this.$http.post('oauth/token', data)
.then(response => {
// authenticate the user
this.$store.dispatch({
type: 'authenticate',
token: response.body.access_token,
expiration: response.body.expires_in + Date.now()
})
// redirect after successful login
if (this.$route.query.from)
this.$router.push(this.$route.query.from)
else
this.$router.push('/feed')
})
}
}
バックエンド(単にページを更新した後に動作します)
setUser() {
// this route throws 'unauthenticated' error
// and works only after refreshing the page
this.$http.get('api/users/')
.then(response => {
this.$store.dispatch({
type: 'setUser',
id: response.body.id,
email: response.body.email,
name: response.body.name
})
})
}
}
Vuexストアからユーザー情報を取得します
export default new Vuex.Store({
state: {
isAuth: !!localStorage.getItem('token'),
user: {
id: localStorage.getItem('id'),
email: localStorage.getItem('email'),
name: localStorage.getItem('name')
}
},
getters: {
isLoggedIn(state) {
return state.isAuth
},
getUser(state) {
return state.user
}
},
mutations: {
authenticate(state, { token, expiration }) {
localStorage.setItem('token', token)
localStorage.setItem('expiration', expiration)
state.isAuth = true
},
setUser(state, { id, email, name }) {
localStorage.setItem('id', id)
localStorage.setItem('email', email)
localStorage.setItem('name', name)
state.user.id = id
state.user.email = email
state.user.name = name
}
},
actions: {
authenticate: ({ commit }, { token, expiration }) => commit('authenticate', { token, expiration }),
setUser: ({ commit }, { id, email, name }) => commit('setUser', { id, email, name })
}
})
Laravel経路
Route::group(['middleware' => 'auth:api'], function() {
Route::get('/users', '[email protected]');
});
Laravel機能
public function users(Request $request)
{
return $request->user();
}
エラーメッセージ
![enter image description here](https://i.stack.imgur.com/VqsXs.png)
ページをリロードすると、エラーメッセージが表示されなくなり、正常に認証されました。
私はどんな助けでも非常にうれしいです!
resposneよりも重要なのは、失敗した呼び出しのリクエストヘッダです。トークンが実際に送信されたことを確認できますか?私が見るところでは、ログイン後にデフォルトのリクエストヘッダを設定していないだけです。おそらく一度アプリケーションの開始時に起こるので、リロード後に動作します –
ありがとうございました!それはまさに問題でした!私はすべての要求とヘッダーを送信していない! – Schwesi