The Next Js 13 API route is failing to retrieve accurate data following a post request

I've been working on a project involving authentication using Django backend and Next.js frontend. For state management, I'm utilizing Redux Toolkit. However, I've encountered an issue with the Next.js API that communicates data to the backend. Here are the actions defined in auth.js that send data to the API:

export const login = (email, password) => async dispatch => {
    const body = JSON.stringify({
        email,
        password
    });
    // alert(`body is ${body}`) //This alert is showing data hence it`s working
    dispatch({
        type: SET_AUTH_LOADING
    });
    try {
        const res = await fetch('/auth/login/api', {
            method: 'POST',
            headers: {
                'Accept': 'application/json',
                'Content-Type': 'application/json'
            },
            body: body
        });
    } catch (error) {

    }
}

Next, here's the API route responsible for interacting with the backend:

export async function POST(request) {
    const res = await request.body;
    console.log (`Response is ${res}`)
    const { email, password } = await request.body;
    const body = JSON.stringify({
        email,
        password
    });
    console.log(`Posted data is: ${body}`)
    return NextResponse.json({ res })
}

The first console.log displays Response is [object Object], followed by the second console.log displaying Posted data is: {}. I am struggling to identify the root cause behind this discrepancy despite the API route being invoked. Any assistance would be greatly appreciated.

Answer №1

In the latest update of Next.js, version 13 made some changes. To handle JSON content, you now use the .json method and await it before proceeding.

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

    const { email, password } = body;
    const bodystring = JSON.stringify({
        email,
        password
    });
    console.log(`The data posted is: ${bodystring}`);
    return NextResponse.json({ res: body });
}

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

Getting a user's group name from Azure Active Directory in an Angular application - a step-by-step guide

I have connected to Azure directory using ng2-adal (https://github.com/mazhisai/ng2-adal-QuickStart) and successfully obtained a group id in the format: "groups":["4ba2649e-20d2-40f4-a406-2ed897686403","43e19f05-c077-4716-b001-0ffb0d75fff8"]. Is there a w ...

What is the best way to utilize a JavaScript function across all pages in Drupal 7?

What is the best way to utilize a global JavaScript function in Drupal 7? I have structured my JavaScript file as follows and included it using drupal_add_js(): (function($) { function add_if_country_is_not_usa() { // Determine the current country ...

Navigating with Node.js and angular

I'm struggling with redirecting POST requests using Node.js, Express, and Angular. Typically, we'd use forms like this: index.ejs <!DOCTYPE html> <html> <head> <title>Redirect Example</title> </head> <bo ...

Embarking on the journey of launching an Angular application on AWS CloudFront

I have a Laravel PHP application that functions as an API accessed by an Angular single-page app. Currently, the Angular app is situated within the public folder, but I aim to separate it so I can deploy it through Amazon CloudFront. I came across this ar ...

How to design a dictionary schema using Mongoose

I have been attempting to save a dictionary of objects using Mongoose. Upon realizing that the change detection for saving is lost when using the Mixed type, I am looking for a way to create a schema that does not rely on the Mixed type. While there are m ...

Tips for setting up the image as the header background in HTML5 and CSS3

I am currently designing a website. I'm wondering if there is a way to create a div with a curved bottom using HTML5, CSS3 and JavaScript. It should resemble the design of the curved header bottom ...

Attempting to spread a non-iterable instance is invalid. For non-array objects to be iterable, they must have a [Symbol.iterator]() method

data(){ return { tables:[] } }, mounted(){ this.fetchData() }, methods:{ fetchData(){ var subscription = web3.eth.subscribe('logs', { address: '0x123456..', topics: ['0x12345. ...

What steps do I need to follow to upload an image file through Socket.IO?

For my school project, I am developing a chat application and facing a challenge with implementing an onClick event to trigger a function that utilizes socket-io-file-upload to prompt the user to select a file for upload. This functionality is detailed in ...

Locking mat-toolbar and mat-tabs to the top in Angular Material 2

As I work on my website, my goal is to fix the < Mat-Toolbar > at the top of the screen and then directly underneath that, lock the < Mat-Tabs >. The challenge I'm facing is that the position: fixed in CSS is not working as expected. When ...

Would you be able to clarify why the run() function is giving me an error when I try to return {1,3}, but it works fine when I return {a,b} in

I'm really confused as to why the return {1,3} in the run() function is throwing an error when it works just fine for return {a,b} in the fun() function function fun(){ let a = 10; let b = 20; return {a, b}; } ...

I require the ability to retrieve only the data from a UI grid column, specifically based on the column name selected

I need help with my angularjs application that utilizes Ui grid. There is an external dropdown menu located outside of the ui grid, which lists all the column names in the grid. I want to be able to select a specific column name from this dropdown and retr ...

Is there a way to make FullPage and Lightbox compatible with each other?

Currently utilizing Fullpage.js for my website, I am looking to incorporate a lightbox in one of the sections. However, upon attempting to load the script and CSS, my fullpage layout breaks and the sections collapse. I have experimented with placing the ...

Trigger a JavaScript function when a key is pressed down

Hey everyone, I'm trying to figure out how to trigger a JavaScript function when a particular key is pressed. For example, I want the function down() to be executed when the down key is pressed and function left() when the left key is pressed. Is ther ...

Stopping Amazon Web Services Lambda functions from running on their own

I've implemented a Lambda function that is triggered whenever a new folder object is created in the root bucket. A unique identifier is generated for each folder object, such as 67459e53-20cb-4e7d-8b7a-10e4cd165a44 Within the root bucket, there is a ...

Anchor no longer follows endpoint after Anchor ID is modified following creation - JSPlumb

I am currently developing an editor that involves placing shapes on a canvas and assigning IDs to them. When a shape is placed, endpoints are automatically created and attached to the shape using its ID as an anchor. //Function responsible for adding en ...

When making an Ajax request to another website, the response received is in HTML format instead of

I am attempting to retrieve an array by making an AJAX GET request to a URL. Below is my controller code, which is hosted locally at localhost:3000 def merchant_ids merchants = Merchant.where(id: params[:id]).pluck(:merchant_name, :id, :merchant_city, ...

The MIME type 'text/html' is incompatible with stylesheet MIME type and is not supported

I have exhausted all possible solutions for the issue, from specifying the type for <link rel="stylesheet" href="./style.css" /> to using app.use(express.static('public')), but unfortunately, none of them seem to resolve the problem. index ...

Capturing user-selected option from dropdown menu using npm

I am a beginner when it comes to node.js and async programming. My current project involves creating a program that shuffles a Spotify playlist. I have managed to store the user's playlists in an array for easier access. My goal is to present this ar ...

What is the best way to apply attributes to all titles throughout a webpage?

My goal is to locate all elements on the page that have a title attribute and add a new attribute to each of them. For example: <div title='something 1'></div> <p>Test<div title='something 2'></div></p ...

Modules imported without the capability of server-side rendering

I'm encountering an issue with Next.js. Whenever I try to import a node module that relies on the window object, Next.js throws an error: window is not defined. The module is being imported in this manner: import * as widgets from 'survey-widget ...