next.js JS无法读取未定义的属性(正在阅读'headers')

fbcarpbf  于 2023-08-04  发布在  其他
关注(0)|答案(1)|浏览(166)

我在后端使用Django rest framework。当用户输入错误的凭证时,我从后端发送400状态。在前端,我使用NEXT.js。在登录route.js时,当状态不是200时,我得到以下错误。
- error TypeError: Cannot read properties of undefined (reading 'headers') at eval (webpack-internal:///(sc_server)/./node_modules/next/dist/server/future/route-modules/app-route/module.js:261:61) at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
route.js的代码是:

import axios from "axios";
import { NextResponse } from "next/server";

export async function POST(request) {
  const body = await request.json();
  // console.log(body);

  try {
    const config = {
      headers: {
        Accept: "application/json",
        "Content-Type": "application/json",
      },
    };

    const response = await axios.post(
      "http://127.0.0.1:8000/app_api/login_user/",
      body,
      config
    );

    // console.log(response.status);
    const data = response.data;
    const { message } = data;
    const nextResponse = new NextResponse(JSON.stringify(data), {
      status: 200,
    });
    const { token } = data;
    nextResponse.cookies.set("token", token, { httpOnly: true, path: "/" });
    return nextResponse;
  } catch (error) {
    if (error.response) {
      console.log("Here: ", error.response.data);
      // console.log(error.response.data);
      // return new NextResponse(error, { status: response.status });
    }
  }
}

字符串
在Python代码中,我以这种方式发送响应:

return Response({
        'error': str(e),
        'message': 'User does not exists, please register first'
    }, status=status.HTTP_400_BAD_REQUEST)


谁能帮我找出这里的问题是什么?

ldfqzlk8

ldfqzlk81#

import axios from "axios";

import { NextResponse, NextCookies } from "next/server";

export async function POST(request) {
const body = await request.json();

 try {
const config = {
  headers: {
    Accept: "application/json",
    "Content-Type": "application/json",
  },
};

const response = await axios.post(
  "http://127.0.0.1:8000/app_api/login_user/",
  body,
  config
);

const data = response.data;
const { token } = data;

const nextResponse = new NextResponse(JSON.stringify(data), {
  status: 200,
});

NextCookies.set(request, "token", token, { httpOnly: true, path: "/" });

return nextResponse;
 } catch (error) {
console.error("Error during POST request:", error);

// Construct an appropriate error response and return it to the client
return new NextResponse(JSON.stringify({ error: "Something went wrong." }), {
  status: 500,
});
}
}

字符串

相关问题