Search code examples
javascriptreduxnext.jsredux-toolkit

Next Js 13 API route not getting the correct data after post request


I am working on an authentication project with Django backend and Next js frontend. I am using redux toolkit for state management and I am having a problem with working on the next js api which sends data to the backend. Here is my actions on auth.js which sends the 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) {

    }
}

And here is my API route which is supposed to communicate 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 returns Response is [object Object] and then the second console.log returns Posted data is: {}. I am unable to figure out what could be the problem since the API route is being called. Any help will be highly appreciated.


Solution

  • Next.js 13 changed some things. For JSON content, you invoke .json method and await it

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