【发布时间】: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