Reputation: 4787
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)
});
}
}
...
Upvotes: 2
Views: 1655
Reputation: 4787
OK, in my case it was an export/import issue.
export default CSRF_TOKEN;
instead of
export { CSRF_TOKEN };
made the trick
Upvotes: 2