What is the best way to handle a ReadableStream for a POST request?

I'm currently working on implementing basic CRUD operations using the latest Next.js 13 route handlers in combination with Prisma using TypeScript.

This is how my POST request handler appears:


export async function POST(req: NextRequest) {
  const clientData: clientToCreate = req.body;

  try {
    const data = await prisma.client.create({
      data: clientData,
    });
    return NextResponse.json(data);
  } catch (e) {
    console.error(e);
    return NextResponse.error(e);
  }
}

In this case, the req.body is

ReadableStream<Uint8Array> | null
and I'm struggling to find a way to parse it to access the contained data. Attempting req.body.json() results in:
Property 'json' does not exist on type 'ReadableStream<Uint8Array>'
.

This is how I construct my request:

interface ApiRequest {
  url: string;
  method: "GET" | "POST" | "PUT" | "DELETE";
  params?: Object;
}

const getRequestUrl = (url: string) => {
  return `${process.env.BASE_API_URL}/${url}`;
};

const defaultHeaders = {
  Accept: "application/json; charset=UTF-8",
  "Content-Type": "application/json",
};

export const apiRequest = async (request: ApiRequest) => {
  return await fetch(getRequestUrl(request.url), {
    headers: defaultHeaders,
    method: request.method,
    body: request?.params ? JSON.stringify(request.params) : undefined,
  })
    .then((response) => response.json())
    .catch((e) => {
      console.error(e);
      throw e;
    });
};

After setting up the request as described above, I use Postman to send a POST request with identical headers. Can you help me identify where the issue might be?

Thank you for your assistance in advance.

Answer №1

To retrieve the content of the body:

const responseBody = await request.json()

Using request.body will result in a ReadableStream Object being returned

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

Encountering an issue when attempting to host a Next.js application on Vercel

Why is it important to regularly do this task as per the instructions provided in the link? Info - Working on creating a highly efficient production build... Note: Next.js now collects completely anonymous telemetry data on user usage. This data helps sha ...

Linking a background image in the body to a specific state in next.js

My aim is to create a pomodoro timer using Next.js and I'm trying to link the body's background image to a state. However, my code isn't functioning properly. This is the code I used to update the body style: import { VscDebugRestart } from ...

Solving runtime JavaScript attribute issues by deciphering TypeScript compiler notifications

Here is a code snippet I am currently working with: <div class="authentication-validation-message-container"> <ng-container *ngIf="email.invalid && (email.dirty || email.touched)"> <div class="validation-error-message" *ngIf=" ...

Select numerous files and conveniently delete them using the angular delete button

Background: In one of my tables, there is a column where users can either choose or upload files as input. I have implemented a feature that allows users to select multiple files at once. Issue at Hand: What I am trying to achieve is to have an 'x&ap ...

The subscribe method in Angular TS may be marked as deprecated, but worry not as it is still

I have developed a function that retrieves new data from a service file each time it is called. Here is how the function looks: onCarChange() { this.carService.getCarData(this.selectedCar).subscribe( async (response: CarData) => { if (response?.d ...

Hide the MaterialTopTabNavigator from view

Is there a way to hide the react native MaterialTopTabNavigator on the screen while still maintaining the swiping functionality between screens? I want the user to be able to swipe between screens but not see the tab navigator itself. const Tab = creat ...

What is the method for including as: :json in your code?

I have a file with the extension .ts, which is part of a Ruby on Rails application. The code in this file looks something like this: export const create = async (params: CreateRequest): Promise<XYZ> => { const response = await request<XYZ> ...

Receiving an error while passing properties to a React component: "Property 'firstName' is not found on type 'Readonly<{}>'."

As a beginner in React, I need some patience I'm attempting to create a simple component where users can input their first and last names, update the values, and see them displayed after clicking a button. However, I keep encountering TypeScript comp ...

Creating a personalized fake database functionality in Angular

Is there a way to implement the fake-db feature in Angular while utilizing this resource? I need it to support an API response structure like the one below for list retrieval. // GET 'api/outlets' { data: [ {'id':1, 'name&ap ...

Who is the intended audience for the "engines" field in an npm package - consumers or developers?

As the creator of an npm library, I have included the current LTS versions of Node.js and npm in the package manifest under the engines field. This ensures that all contributors use the same versions I utilized for development: Node.js <a href="/cdn-cgi ...

Using ts-loader with Webpack 2 will result in compatibility issues

Lately, I've been working on setting up a basic Angular 2 (TypeScript) application with Webpack 2 for bundling. However, I'm encountering numerous errors when using ts-loader to process TypeScript (.ts) files. It seems like ts-loader is not excl ...

The error message "Next.js: rt.toLowerCase is not a function" indicates a problem

Upon creating a fresh next.js application using version 14.2.1, I encountered the following error: uncaughtException: TypeError: rt.toLowerCase is not a function at C:\Users\Mohamed\Desktop\next_projects\ecommerce\ecommer ...

What is the reason for TypeScript's decision to lazily evaluate constrained class generics?

I am experiencing confusion with the TypeScript declaration provided below. class C<T extends {}> { method() { type X = T extends {} ? true : false; // ^? type X = T extends {} ? true : false; // Why is X not `true`? ...

replace the tsconfig.json file with the one provided in the package

While working on my React app and installing a third-party package using TypeScript, I encountered an error message that said: Class constructor Name cannot be invoked without 'new' I attempted to declare a variable with 'new', but tha ...

The issue with Angular2 Material select dropdown is that it remains open even after being toggled

Exploring the world of Node.js, I am delving into utilizing the dropdown feature from Angular Material. However, an issue arises once the dropdown is opened - it cannot be closed by simply clicking another region of the page. Additionally, the dropdown lis ...

Running Nextjs on Hostinger servers

Currently, I am trying to host my Next.js website on Hostinger. To achieve this, I have exported Next.js as static files in the 'out' directory using the output: 'export' configuration in the next config. After uploading the static fil ...

Employing Class Categories in Static Procedures

I am currently working on developing a foundational Model that will serve as the base for a specific model class, which will have an interface detailing its attributes. Within the base Model class, I am aiming to incorporate a static factory() function th ...

Angular 6 does not automatically include the X-XSRF-TOKEN header in its HTTP requests

Despite thoroughly reading the documentation and searching for answers on various platforms, I am still facing issues with Angular's XSRF mechanism. I cannot seem to get the X-XSRF-TOKEN header automatically appended when making a POST request. My si ...

Whenever I attempt to host my Node.js app using the GCP deploy command, it fails to work properly. The error message that appears states: "Module 'express' cannot be found."

My NodeJS application is written in TypeScript and utilizes the Express framework. I'm looking to host it on the GCP cloud using the gcloud app deploy command. First, I compile my TS sources to JavaScript - is this the correct approach? Afterwards, I ...

Exploring JSON parsing capabilities in Next.js

As a newcomer to Javascript, I have a query that may seem silly. I am attempting to parse JSON in the main function of Nextjs. However, when I try to parse JSON in the main function before the return statement, I encounter the error SyntaxError: Unexpected ...