The Post method in Next.js API does not display any data on the specified endpoint

Whenever I attempt to send a POST request from my frontend within a Next.js project (using TypeScript), the JSON data I expect at my API endpoint does not appear. Instead, all I see is an empty hyperlink that leads nowhere.

The code for my API is placed in the required pages/api/ folder within the project:

import { NextApiRequest, NextApiResponse } from 'next';

export default async function handler(req: NextApiRequest, res: NextApiResponse) {
  try {
    const data = req.body;
    console.log('from ui', data);
    res.status(200).json(data);
  } catch (error) {
    console.error(error);
    res.status(500).json({ error: 'Internal Server Error' });
  }
}

On the frontend side:

fetch(`/api/checked-projects`, {
      method: "POST",
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(updatedCheckedProjects)
    })
      .then((response) => {
        if (response.ok) {
          return response.json();
        } else {
          throw new Error('Failed to post project data.');
        }
      })
      .then((data: any) => {
        console.log('Received data:', data);
      })
      .catch((error) => {
        console.error(error);
      });

Interestingly enough, console.log('from ui', data); displays the JSON data:

from ui { data: [ 1, 2, 3, 4 ] }

Even more puzzling is that when I manually insert this data into

res.status(200).json({ data: [1, 2, 3, 4] });
, the information appears correctly at the endpoint.

Answer №1

One possible solution is to address the server-side code with the following adjustments:

export default async function handler(req: NextApiRequest, res: NextApiResponse) {
try {
    const receivedData = req.body;
    console.log('Data from UI:', receivedData);
    res.setHeader('Content-Type', 'application/json');
    const jsonData = JSON.stringify(receivedData);
    res.status(200).json(jsonData);
} catch (error) {
    console.error(error);
    res.status(500).json({ error: 'Internal Server Error' });
}

}

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

Trouble encountered with Angular Google Maps integration when using router-outlet

Currently, I am in the process of developing an application that features a map as its header (providing a global view) and another map positioned in the center of the page to showcase detailed views. To demonstrate this setup, I have shared a working exam ...

What is the reason behind my styled component only displaying the final state in its className logs?

Here is my implementation using styled components with the version "@types/styled-components": "^5.1.26" and I'll provide you with an example of my code. // index.tsx import React, { useEffect, useState } from 'react'; i ...

Reducing image file sizes in Ionic 3

I have been struggling to compress an image client-side using Ionic 3 for the past couple of days. I have experimented with: ng2-img-max - encountered an error when utilizing the blue-imp-canvas-to-blob canvas.toBlob() method (which is a dependency of ng2 ...

What is the best way to organize images when adding them to the Strapi media library?

I am facing an issue with the order of images while uploading them using a drag and drop file input in my post car form. Currently, the images are being uploaded to strapi in the order of their size, from larger to smaller. Is there a way to upload them b ...

Error: Unable to locate module - The specified file cannot be resolved when utilizing an external JavaScript library

I am currently integrating a WYSIWYG editor (TUI Editor) into my Angular2+ application. Since there is no official Angular wrapper available, I have decided to create my own based on an existing wrapper. Due to some installation issues with npm, I saved t ...

Oops! An issue has occurred: Unable to locate a differ that supports the object '[object Object]' with the type 'object' within Angular

What am I doing wrong? It's working but I got this error in my console. My Model: export class Form { id: number; formTaxID: number; name: string; formYear: number; sectionID: number; createdAt?: Date; updatedAt?: Date; } My Service: ...

NextJS struggles to load EditorJS plugins

I am currently working on integrating EditorJS into my NextJS project. The editor is loading properly without any plugins, with only paragraph as a block option. However, I'm facing an issue when trying to add plugins using the tools prop which result ...

writeFileSync does not generate or add data to file

I currently have multiple SSG pages in my Next.js project and I am working on creating the navigation menu with various routes. I want to optimize this process by "caching" the first API call and retrieving the saved data from a file for subsequent request ...

Show the distinct values of a mat-select element that retrieves information from an Angular filtered dataSource

Working on an Angular 9 app where data is displayed using a mat-table and filtered based on certain fields. The issue I'm facing is that the dropdown menu shows duplicate values, which is expected since some values may be repeated in the dataset. The ...

A versatile function capable of invoking two APIs simultaneously, with one of them being designed to return an array

Here is the code snippet that I am working with: getElements(apiUrl: string): Observable<Element[]> { return this.httpClient.get<any>(apiUrl + 'test/elements').pipe( catchError(error => { if(error.status === ...

Can a string array be transformed into a union type of string literals?

Can we transform this code snippet into something like the following? const array = ['a', 'b', 'c']; // this will change dynamically, may sometimes be ['a', 'e', 'f'] const readonlyArray = arr ...

Navbar tab toggle with HeadlessUI

Currently, I have implemented a Tabs-Section using headlessui. Within my Navbar, there are Links/Buttons corresponding to each Tab. However, I am encountering an issue in controlling the Tabs using the buttons/links within the Navbar. The Tabs are also bei ...

Creating callback functions that vary based on input variables

Consider the following code snippet, which may seem somewhat contrived: arbitraryFunction( // Input that is dynamically generated [ returnValue("key1", "a"), returnValue("key2", 1), returnValue ...

Configuring global runtime variables in NextJS for server-side operations

Currently, I am utilizing the instrumentation.ts file in NextJS to retrieve configuration dynamically when the server starts up. My goal is to have this configuration accessible during runtime for all API routes and server-side components. What would be th ...

Ways to trigger a page refresh in next.js when the router pushes the same route with a distinct query parameter

Currently working on a product detail page using the route /product?id=xxx. When the user is on /product?id=1 and switches to /product?id=2, only the state dependency router.query.id changes. I am looking for a way to perform a complete page reload inste ...

The type 'string' cannot be assigned to type 'ImageSourcePropType'

Context Attempting to utilize a SVG component in React Native with the xlinkHref property within an Image tag. The SVG file was converted into a React Native Component (TSX) using the tool provided at . While simple SVG icons have been successfully used be ...

Seamless Authentication - automatic login following registration

Are there any resources available on automatically signing in a user after they have signed up? I could only come up with one potential solution: signing up the user first and then programmatically calling the signIn function provided by next-auth to log ...

I've successfully set up my project with strapi and next.js, however I am encountering an issue where the data is not being updated in my application when changes are made in strapi

After successfully setting up strapi and next.js, I encountered an issue where the data fetched initially is not updated when changes are made in strapi. It seems to retain the original data from the first build. Here's my updated solution: --updated ...

Synchronize Docker volumes

Hey there! I've been trying to dive into learning Docker, but I'm having trouble syncing the host and container using volumes when making changes and saving code (specifically using npm run dev). Every time I need to restart docker-compose up --b ...

Managing and utilizing various Angular applications simultaneously

I am new to Angular and I'm exploring the possibility of accessing another application that is hosted on a different port, has its own repository, and uses a different version of Angular. Let's assume I have two Angular Typescript projects named ...