Rails APIとNuxt.jsの環境にて、devise_token_authを使ってログインできる仕組みを構築しようとしていました。
しかし・・・
axiosでresponse.headersが取得できない問題
ログインするためにemail, passwordをpostして、レスポンスヘッダーよりaccess-token, client, uidを取得したかった。
しかし、response.dataが返って来ることは確認できるもののresponse.headersが見当たらない…
this.$axios .$post('/api/v1/auth/sign_in', { email: this.email, password: this.password }) .then((response) => { console.log(response) console.log(response.headers) })
Axios get access to response header fieldsには同現象についてCORSが問題なと指摘がありますが。私はrailsのrack-corsにて設定済みでした。
rack-corsのexposeとaxiosのpostから$をなくした
cors自体は設定していましたが、次のようにexposeで表示を許可するheader情報を指定する必要はありました。これが1ステップ。
config.middleware.insert_before 0, Rack::Cors do allow do origins '*' resource "*", headers: :any, methods: [:get, :post, :put, :patch, :delete, :options, :head] expose: ['access-token', 'client', 'uid'] end end
もう一つ、responseにheadersを表示させる方法ですが、Nuxt.jsのaxiosの記述を変える必要がありました。
具体的には$postをpostに変えました($を取り除いた)。
this.$axios .post('/api/v1/auth/sign_in', { email: this.email, password: this.password })
これでレスポンスデータにheadersが現れました。