Just dipping my toes into the world of Nextjs while tinkering with a frontend interface for my trusty Django app
Let's take a peek at my route.js file where the magic happens, as it makes a call to the django endpoint
import { NextResponse } from 'next/server';
import axios from 'axios';
//import { cookies } from 'next/headers';
export async function POST(req: Request) {
const { imageData } = req.body;
try {
//Behold! The Django backend
const response = await axios.post(
'http://localhost:8000/souci/capture/',
{ imageData }
);
return NextResponse.json({response});
} catch (error) {
console.error('Uh-oh! Error sending image data to Django:', error);
return NextResponse.json({ success: false, error: 'Failed to send image data to Django' });
}
}
export async function GET(req: Request) {
//Silence...for now
}
A perplexing issue arises on my Django console like a whisper in the wind
WARNING:django.security.csrf:Forbidden (CSRF cookie not set.): /souci/capture/
[20/Feb/2024 04:55:44] "POST /souci/capture/ HTTP/1.1" 403 2870
How can I tame this CSRF token quandary within the confines of the POST function?
Delving into solutions, including tweaking axios defaults and such
axios.defaults.xsrfCookieName = 'csrftoken'
axios.defaults.xsrfHeaderName = "X-CSRFTOKEN"
Toying with cookie creation (yet unsure how to seamlessly integrate it with the POST request)
cookies().set('csrftoken', 'souci', {
maxAge: 60 * 60 * 24, //one day in seconds
httpOnly: true, // prevent client-side access
sameSite: 'strict',
});