简体   繁体   中英

Django + VueJS: POST 403 Forbidden - CSRF token missing or incorrect

I am running Django + Django REST framework in the backend and Vue.js in the frontend. GET requests work fine, POST requests via Postman/Insomnia also do, but POST requests via the Vue.js frontend return an error in the Browser console:

POST http://127.0.0.1:8000/api/questions/ 403 (Forbidden)
{detail: "CSRF Failed: CSRF token missing or incorrect."}

This is how I get the CSRF token and then fetch a POST request:

File: csrf_token.js:

import Cookies from "js-cookie";
var CSRF_TOKEN = Cookies.get("csrftoken");
export { CSRF_TOKEN };

File: api.service.js :

import CSRF_TOKEN from "./csrf_token.js";

async function getJSON(response) {
  if (response.status === 204) return "";
  return response.json();
}

function apiService(endpoint, method, data) {
  const config = {
    credentials: "same-origin",
    method: method || "GET",
    body: data !== undefined ? JSON.stringify(data) : null,
    headers: {
      "content-type": "application/json",
      "X-CSRFToken": CSRF_TOKEN
    }
  };
  return fetch(endpoint, config)
    .then(getJSON)
    .catch(error => console.log(error));
}

export { apiService };

MyComponent.vue:

...
methods: {
  onSubmit() {
    apiService(endpoint, method, { content: this.content })
      .then(response_content => {
        console.log(response_content)   
      });
  }
}
...

OK, in my case it was an export/import issue.

export default CSRF_TOKEN;

instead of

export { CSRF_TOKEN };

made the trick

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM