![](/img/trans.png)
[英]Forbidden (CSRF token missing or incorrect.) during ajax POST in Django
[英]Django + VueJS: POST 403 Forbidden - CSRF token missing or incorrect
我在后端運行 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 };
我的組件.vue:
...
methods: {
onSubmit() {
apiService(endpoint, method, { content: this.content })
.then(response_content => {
console.log(response_content)
});
}
}
...
好的,就我而言,這是一個導出/導入問題。
export default CSRF_TOKEN;
代替
export { CSRF_TOKEN };
成功了
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.