When my route in NextJS processes the request, it returns a ReadableStream from req

I am encountering an issue with my code and I have tried looking for solutions in other similar questions without any success. Is there anyone who can assist me?

Here is the content of my route.js file:

import dbConnect from "@/lib/dbConnect";
import User from "@/models/User";
import { NextResponse, NextRequest } from "next/server";
import type { NextApiResponse, NextApiRequest } from "next";

export async function POST(req: NextApiRequest) {
  await dbConnect();
  let data = await req.body;
  console.log(data); //HERE ReadableStream { locked: false, state: 'readable', supportsBYOB: false } HERE

  try {
    const user = await new User(data);
    await user.save();

    return NextResponse.json({ user }, { status: 201 });
  } catch (error) {
    console.log("here 3");
    if (error instanceof Error) {
      return NextResponse.json(
        { error: error.message || "unknown error" },
        { status: 500 }
      );
    } else {
      return NextResponse.json(
        { error: "unknown error" },
        { status: 500 }
      );
    }
  }
}

Below is the request I made:

try {
      const res = await fetch("http://localhost:3000/api/register", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(data),
      });

      const dataRes = await res.json();
      console.log("dataRes" + dataRes);
    } catch (error) {
      console.log(error);
    }

Answer №1

Make sure your route handler is set up to accept the Request type rather than NextApiRequest.

export async function POST(req: Request) {
  // ...
}

This allows you to handle the request body in any way you see fit, such as using the Request#json method.

export async function POST(req: Request) {
  // ...
  let data = await req.json();
  // ...
}

You can find more information on this topic in the Next.js documentation here.

Additionally, make sure you are returning standard Response objects instead of NextResponse, as explained in the documentation mentioned above.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Determine the height of an element in JavaScript or jQuery by using the CSS property height: 0;

I'm facing a challenge in determining the actual height of an element, which currently has a CSS height property set to: height: 0; When I check the console, it shows a height of 0, but I'm looking to find the real height of the element. I als ...

What is the correct way to invoke a function from a different file?

Having trouble calling a function from another file in my JS code. I am unable to call a function from another js file. I suspect there is an issue with linking the two files. Code snippet from my first JS file const { response } = require('expre ...

The IE9 confirmation dialog fails to pause for user response, resulting in automatic postback before user input is received

Behind the Scenes btnNext.Attributes.Add("onclick", " return Verification(this,'" + GetLocalResourceObject("message").ToString() + "'); ") .ASPX Page [Within javascript tags] function Verification(source, message) { var dialog = '< ...

Angular App Failing to Validate Session Cookie 'sessionId' in AuthGuard

Encountering a perplexing issue with my Angular application where the AuthGuard fails to recognize a session cookie named 'sessionId' correctly. I have successfully implemented user authentication, and the expected behavior is for users to be dir ...

Tips for uploading images in Next.js using Firebase

While following a tutorial on Next.js, I encountered an issue with the outdated version of Firebase being used. Despite trying different solutions from the documentation and various sources, I am still facing an error message while attempting to upload ima ...

Error encountered while attempting to clone repository in AWS Amplify: "SSR apps do not support Basic Auth."

My AWS Amplify app has restricted access control set up with credentials in the app settings. However, I noticed that when I temporarily turn off the restrictions to make it publicly viewable and then try to turn them back on again, the build fails in AW ...

AgGrid Encounters Difficulty in Recovering Original Grid Information

After making an initial API call, I populate the grid with data. One of the fields that is editable is the Price cell. If I edit a Price cell and then click the Restore button, the original dataset is restored. However, if I edit a Price cell again, the ...

Adjust the height for just one md-tab

Looking to find a way to set the height of the content within an <md-tab> element to be 100% in a flexible manner. For example, consider the following structure: <body> <md-content> <md-tabs> <md-tab label= ...

Ways to specify the styles for tr, td, and label elements within a material table

Hey there! Currently, I'm working with material table in react. I came across this page: https://material-table.com/#/docs/features/styling, where it mentions that we can use cellStyle, headerStyle. But what if I want to add more detailed styles to e ...

Add delayed event listeners to embedded AJAX request beyond function boundaries

I'm working on developing a custom AJAX method extension named getApi that automatically includes my authentication bearer token in the request header. In my code, there is a function called getToken() which retrieves the token either from sessionSto ...

What steps can I take to prevent encountering a Typescript Error (TS2345) within the StatePropertyAccessor of the Microsoft Bot Framework while setting a property?

During the process of constructing a bot in Typescript, I encountered TS2345 error with Typescript version 3.7.2. This error is causing issues when attempting to create properties dynamically, even if they are undefined, or referencing them in the statePro ...

Guide to dynamically loading customer data into an HTML table using JavaScript

I'm looking to populate a table with data on customers including their name, customer ID, and rental cost. Can anyone help me with the JavaScript code needed to insert this data into rows of the table? Your assistance is greatly appreciated. Below is ...

Is it possible to create a hyperlink in the <button> element?

Having been immersed in HTML5 for quite a while now, I recently encountered a challenge while working on my login/register page project. I wanted to create a button that would redirect me to another HTML page upon clicking. While I am familiar with the < ...

The text color remains the same even after the method has returned a value

I have a vuex query that returns a list of books. I want to display each book with a specific color based on its status. I tried using a method to determine the color name for each book and bind it to the v-icon, but it's not working as expected - no ...

Exploring Array Iteration: Navigating through Arrays with the .map Method in React and Vue

I am currently using Vue after coming from a React background. In React, there is a method called .map that allows you to render a component multiple times based on the number of items in an array and extract data from each index. Here's an example: f ...

How can I use AJAX to read an image file and display it on a Canvas?

Is there a way to read an image from my server using Ajax and then display it on Canvas? I am aware that this can be achieved by using normal image tags and canvas draw methods, as shown below: <img id="myImage" src="./ColorTable.PNG" style="display:n ...

The "scrollTop" function seems to be malfunctioning in Firefox but works perfectly fine in Chrome. Is there a way to fix this issue?

Issue with scrollTop in Firefox jQuery(window).scroll(function(){ var NextScroll = jQuery(this).scrollTop(); if (NextScroll >= 800){ jQuery('#logomacchia').addClass("maccancello"); } else { jQuery('#logomacch ...

Display the div if the input field is left blank

Is there a way to display the div element with id="showDiv" only if the input field with id="textfield" is empty? <form action=""> <fieldset> <input type="text" id="textfield" value=""> </fieldset> </form> <div id="sh ...

Arranging the data in the table by alternating rows using Datatables

I need to organize my data in a way that includes an additional row for descriptive information, but this particular row should not be sorted. It is crucial for understanding the rest of the data, so hiding or showing it is not an option. Is it possible t ...

The smooth transition of my collapsible item is compromised when closing, causing the bottom border to abruptly jump to the top

Recently, I implemented a collapsible feature using React and it's functioning well. However, one issue I encountered is that when the collapsible div closes, it doesn't smoothly collapse with the border bottom moving up as smoothly as it opens. ...