[英]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.我在后端运行 Django + Django REST 框架,在前端运行 Vue.js。 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: 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."}
This is how I get the CSRF token and then fetch a POST request:这就是我获取 CSRF 令牌然后获取 POST 请求的方式:
File: csrf_token.js:文件:csrf_token.js:
import Cookies from "js-cookie";
var CSRF_TOKEN = Cookies.get("csrftoken");
export { CSRF_TOKEN };
File: api.service.js :文件: 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:我的组件.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成功了
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.