[DRF + Vue.js] Error when getting API (general mistake)

Introduction

An error occurred when getting the API created by DRF with axios etc. from within the Vue component as shown below.

javascript:.../source/views/Mypage.vue


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

Error that occurred

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.

The content is that the access of XMLHttpRequest from Vue is blocked on the DRF side. Checking the CORS settings, the settings are as follows.

python:.../settings.py


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

Solution

I forgot to add a'/' at the end of the request URL. Therefore, you can modify the Vue component file as follows.

javascript:.../source/views/Mypage.vue


export default {
  ...
  ...
  mounted() {
    //Finally'/'To add
    api.get("/users/" + this.user_id + '/').then(response => {       
      this.Person = response.data
    })
  }
};

Recommended Posts

[DRF + Vue.js] Error when getting API (general mistake)
Send data to DRF API with Vue.js