如何在nextjs中为django设置CSRF cookie

问题描述 投票:0回答:1

我是 Nextjs 新手,正在为我的 Django 应用程序开发前端

这是我的 Route.js 调用 django 端点

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 {

    //Django backend

    const response = await axios.post(
      'http://localhost:8000/souci/capture/', 
      { imageData }
    );

    return NextResponse.json({response});
  } catch (error) {
    console.error('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) {
  //return
}

我目前在 Django 控制台上收到此错误

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

如何在POST函数中设置csrftoken?

我尝试了一些方法,包括设置 axios 默认值

axios.defaults.xsrfCookieName = 'csrftoken'
axios.defaults.xsrfHeaderName = "X-CSRFTOKEN"

创建 cookie(尽管不确定如何将其添加到 POST 请求中)

cookies().set('csrftoken', 'souci', {
  maxAge: 60 * 60 * 24, //one day in seconds
  httpOnly: true, // prevent client-side access
  sameSite: 'strict',
});
django typescript next.js cookies next.js14
1个回答
0
投票

您可以使用此 Javascript 函数创建

csrf_token

function getToken(name) {
    let cookieValue = null;
    if (document.cookie && document.cookie !== '') {
        const cookies = document.cookie.split(';');
        for (let i = 0; i < cookies.length; i++) {
            const cookie = cookies[i].trim();
            // Does this cookie string begin with the name we want?
            if (cookie.substring(0, name.length + 1) === (name + '=')) {
                cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                break;
            }
        }
    }
    return cookieValue;
}

const csrftoken = getToken('csrftoken');
© www.soinside.com 2019 - 2024. All rights reserved.