【问题标题】:Django + VueJS: POST 403 Forbidden - CSRF token missing or incorrectDjango + VueJS:POST 403 Forbidden - CSRF 令牌丢失或不正确
【发布时间】:2019-12-03 16:29:45
【问题描述】:

我在后端运行 Django + Django REST 框架,在前端运行 Vue.js。 GET 请求可以正常工作,通过 Postman/Insomnia 的 POST 请求也可以,但是通过 Vue.js 前端的 POST 请求会在浏览器控制台中返回错误:

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

这就是我获取 CSRF 令牌然后获取 POST 请求的方式:

文件:csrf_token.js:

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

文件: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)   
      });
  }
}
...

【问题讨论】:

    标签: javascript python django vue.js csrf


    【解决方案1】:

    好的,就我而言,这是一个导出/导入问题。

    export default CSRF_TOKEN;
    

    而不是

    export { CSRF_TOKEN };
    

    成功了

    【讨论】:

      猜你喜欢
      • 2013-12-03
      • 2013-08-15
      • 2015-10-15
      • 2017-09-10
      • 2021-07-14
      • 2019-12-22
      • 2018-11-05
      • 2021-11-13
      • 2012-04-20
      相关资源
      最近更新 更多