0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

【DRF + Vue.js 】API取得時のエラーについて

Last updated at Posted at 2020-08-07

はじめに

 Vueのコンポーネント内から、DRFで作成したAPIを以下のようにaxiosなどで取得する際にエラーが発生した。

.../source/views/Mypage.vue
export default {
  ...
  ...
  mounted() {
    this.axios.get("/users/" + this.user_id).then(response => {
      this.Person = response.data
    })
  }
};

発生したエラー

Access to XMLHttpRequest at 'http://127.0.0.1:8000/XXX/XXX/XXX' from origin 'http://127.0.0.1:8080' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: Redirect is not allowed for a preflight request.

VueからのXMLHttpRequestのアクセスがDRF側でブロックされているという感じの内容である。
CORSの設定を確認すると、以下の様にしっかり設定できている。

.../settings.py
CORS_ORIGIN_ALLOW_ALL = False
CORS_ORIGIN_WHITELIST = (
    'http://localhost:8080',
    'http://127.0.0.1:8080',
)

解決

リクエスト先のURLで最後に '/' をつけるのを忘れていた。
したがって、Vueのコンポーネントファイルを以下の様に修正すればよい。

.../source/views/Mypage.vue
export default {
  ...
  ...
  mounted() {
    // 最後に'/'を追加する
    api.get("/users/" + this.user_id + '/').then(response => {       
      this.Person = response.data
    })
  }
};
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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?