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

Can you tell me if this falls under a POST or GET request?

I found this code snippet on a coding website. I'm curious, would you classify this as a POST request or a GET request? The only modification I made was changing the action location to direct to a Java servlet instead of PHP. <!DOCTYPE html> &l ...

Top method for combining several external JavaScript libraries into a single one using webpack

Recently, I was diving into the world of webpack tutorial and it struck me that in order to combine everything into one module, scripts need to use require('./xyz'). Until now, I've always written individual scripts and loaded them in HTML u ...

Using Javascript to organize data in a table

I have a basic HTML table setup that looks like this: <table id="myTable"> <thead> <tr> <th class="pointer" onClick="sortTable()">Number</th> <th>Example3</th> <th ...

JavaScript, JQuery, and the Observer Design Pattern

Currently, I am in the process of developing a third-party application specifically for certain websites using Jquery. Lately, I have incorporated rx.Observable into my project. However, grasping the utilization of this new JS library has proven to be qui ...

Can you explain the distinction between locating an element by its class name versus locating it by its CSS selector?

Class name: var x = document.getElementsByClassName("intro"); CSS selector: var x = document.querySelectorAll("p.intro"); I'm a bit puzzled, are there any distinctions between the two methods or are they essentially the same? ...

Transforming a JSON structure into a tree model for use with the angular-tree-control component

I need help converting a complex JSON schema into a format compatible with Angular Tree Control. The issue is that the schema does not follow the required treemodel structure for Angular Tree Control, particularly because the children in the schema are not ...

Utilize jQuery to serialize the HTML input elements that are dynamically generated outside of the form

A proof of concept is in progress for an application that involves the generation of HTML elements based on user-configured fields. Here is a sample configuration: // Customer SAM $response = array( array ( NAME => CUSTOMER, TYPE = ...

What is the alternative to using document.getElementById?

1) Question 1 Why does the following example work without using "document.getElementById('myId')" and is it acceptable to skip this step? <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Javascript quest ...

Having difficulty generating a footer for a page that includes a Material-UI Drawer component

Looking to create a standard full-width footer at the bottom of my page, I need help with the implementation. Utilizing the "Permanent drawer" from Material-UI Drawer for reference here. If you're interested in experimenting with it, CodeSandbox link ...

What is the best way to access the form button inside a div element?

Here is the code snippet for my form: <form accept-charset="utf-8" action="https:example.com" method="get" name="test"> <div class="classy"><input type="button" class="buttonE ...

Is there a way to trigger the activation of the datepicker during the `onLoad` event?

For my project, I am utilizing this datepicker. While I am familiar with using scripts to handle changes in the date value, I am unsure of how to implement it on page load. $('.date_set .date').datepicker({ startView : 0, ...

Flask and the steps to modify CORS header

While working on my localhost, I came across a CORS error when building an application to handle search queries for a different domain. The specific error was: "Cross Origin Request Blocked... (Reason: CORS header 'Access-Control-Allow-Origin' mi ...

The daily scripture quote from the ourmanna.com API may occasionally fail to appear

I've been trying to display the daily verse from ourmanna.com API using a combination of HTML and JS code, but I'm encountering an issue where the verse doesn't always show up. I'm not sure if this problem is on the side of their API or ...

Use Express 4.x to automatically redirect HTTP traffic to HTTPS

Here is the code snippet that I am working with: var https = require('https'); var http = require('http'); var express = require('express'); var app = express(); var router = express.Router() ...

PHP MySQL - Automatically trigger email notification upon insertion of a new record

Is there a way to trigger an email alert only when a new record is added, not when the user edits input fields in a table? The database I'm working with stores equipment delivery dates. Users schedule deliveries and input the dates into a SQL Server ...

I am trying to showcase a collection of images on my homepage, but unfortunately, it is not functioning as expected

Does anyone know how to display images using Angular? I am currently utilizing the pic controller in an AngularJS file. Any assistance would be greatly appreciated. HTML CODE <!DOCTYPE html> <html> <head> <meta charset="utf-8"& ...

What is the best way to showcase the output of a Perl script on a webpage

I recently came across a resource discussing the process of executing a perl script from a webpage. What is the best way to run a perl script from a webpage? However, I am facing a situation where the script I have takes more than 30 seconds to run and d ...

The timeouts persist in firing and running even after being cleared and the component has been unmounted

I am currently working on creating bus animations based on an array of coordinates. I am using setTimeout to trigger a function that moves the marker to the next coordinate. However, I am facing an issue where the functions continue to execute even after c ...

What is the best method for displaying the accurate calculated value based on an element?

Within my "ROI calculator," there is a feature that allows users to adjust different labels. One of these labels is called "onlineRevenue." The concept is to recommend the most suitable plan based on the user's online revenue. However, I have some re ...

Creating an HTTPS server that can be accessed via my specific IP address

My attempt to create ad hoc and OpenSSL based certificates in Python Flask was inspired by a tutorial I found on this website. I also explored the method of creating root CA, trusting it, and generating certificates as outlined on this GitHub thread using ...