Encountering a problem when trying to send an API request to the server in the latest version of

I am a newcomer to NextJS 13 and I am facing an issue with my files in the app. Despite my efforts to look for solutions online and study tutorials to keep up with the latest updates, I have not been successful in resolving the problem.

The endpoint I am trying to access is located at src/app/contact-route/route.js with the following code:


            export async function postHandler(req, res) {
                try {
                    const { data } = req.body;
                    console.log("DATA FROM BCK", data);
                    res.status(200).json({ message: 'Data received successfully!' });
                } catch (error) {
                    res.status(500).json({ error: 'failed to load data' });
                }
            }

            export default async function handler(req, res) {
                if (req.method === "POST") {
                    return postHandler(req, res);
                } else {
                    res.status(405).json({ message: 'This method is not allowed' });
                }
            }
        
    

Additionally, my contact page file, src/app/contact/page.js, consists of the following code:


            // Contact page JavaScript code goes here
        
    

When attempting to make a POST request to the endpoint src/app/contact-route/route.js, I encounter these errors:


            ⨯ Detected default export in '/Users/path-to-file/src/app/contact-route/route.js'. Export a named export for each HTTP method instead.
            ⨯ No HTTP methods exported in '/Users/path-to-file/src/app/contact-route/route.js'. Export a named export for each HTTP method.
        
    

and


            POST http://localhost:3000/app/contact-route 404 (Not Found)
            SyntaxError: Unexpected token '<', "<!DOCTYPE ..." is not valid JSON
        
    

If anyone can assist me in resolving this issue, I would greatly appreciate it. Thank you!

Answer №1

Almost had it!

In next.js version 13, API functions must be named after HTTP methods like GET, POST, DELETE...

If you check your network, you'll notice a 405 error (method not allowed)

Simply change

export async function postHandler(req, res) {

to
export async function POST(req, res) {

Just to clarify, if you want it to be a GET request, the function name should be GET(req,res)

If you want it to support multiple methods, all you have to do is:

function ANYNAME(req,res){}

export {ANYNAME as GET, ANYNAME as POST}

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

Guide to putting a new track at the start of a jPlayer playlist

I am currently working on a website that utilizes the jPlayer playlist feature. I am facing an issue, as I need to implement a function that adds a song to the beginning of the playlist, but the existing add function only appends songs to the end of the pl ...

Import ES6 code by wrapping it in parentheses

Currently delving into React Native and I'm intrigued by the parentheses used in the first line of import. import React, { Component } from 'react'; import { AppRegistry, Text } from 'react-native'; class HelloWorldApp extends Co ...

Designing an arrangement using JavaScript and CSS to encase text

Imagine you have an image positioned to the left using float:left;, with text flowing around it. The solution seems simple enough: <img src="image.jpg" style="float:left"> <p style="outline: 1px dotted blue">Lorem ipsum...</p> However, ...

How to automatically update checkbox status in Kendo UI Treeview when connected to a local dataset

A JavaScript object I'm working with contains an items array that defines a hierarchy. When I use this data to create a kendoTreeView widget and set loadOnDemand to false, the checkboxes that are supposed to be indeterminate appear unchecked instead. ...

Tips on how to remove the first column from a jQuery hover effect

Currently, I have a function that enables hover events on a table. Right now, it excludes the header row but I also need it to exclude the first column. Any suggestions on how to do this? $(".GridViewStyle > tbody > tr:not(:has(table, th))") ...

Optimizing server layout components with NextJS's on-demand revalidation feature

I recently began developing a new application with NextJS 13 and MongoDB. This app features a dynamic navigation menu whose elements are determined by a configuration object stored in the database. Currently, the navigation menu is integrated into a server ...

Creating a basic voting system with Vue.js and Firebase: A step-by-step guide

Hello, and please forgive me if this question seems too basic, but I'm just starting out and feeling a bit overwhelmed. I'm attempting to allow a user to vote on and then remove their vote from an item posted by another user using the same butto ...

Passing backend variables/data to AngularJS in Express JS

As a newcomer to express js, I appreciate your patience with me. I've been diving into "MEAN Web Development" by Amos Q. Haviv and finding it to be an excellent read. However, there's one part that's leaving me puzzled. It seems that in or ...

Attempting to render an image onto a canvas and apply Caman.js for image editing purposes

Currently, I have a code snippet that allows me to draw an image onto a canvas. Here is the code: var imageLoader = document.getElementById('imageLoader'); imageLoader.addEventListener('change', handleImage, false); var ...

Tips for updating the icon based on the active or inactive status in ag-grid within an angular application

HTML* <ng-template #actionButtons let-data="data"> <div class="cell-actions"> <a href="javascript:;" (click)="assign()"> <i nz-icon nzType="user-add" nzTheme= ...

Finding the most recent instance of a deeply buried value based on a specific property

I have an example object: const obj = { group: { data: { data: [ { id: null, value: 'someValue', data: 'someData' } ...

Fluidly adjust text field and label fields in forms

I came across a code snippet that allows for dynamically adding form text fields. However, I needed to ensure that each text field has a corresponding label which increments by one every time a new field is added. While I have successfully added the labels ...

Pass information from one .jsp file to a JavaScript function in another .jsp file

Here is the content of OneEmployee.jsp: <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %> <form> <td> <c:out value="${emp.getEmpid()}"/></td> <td> <input type="text" id="fname" value="<c:out v ...

Trouble arises when displaying data using AngularJS in an HTML environment

I'm currently facing a challenge understanding where I went wrong in my code. My goal is to display the initial array values in the table data, but so far, I haven't had much success. Here is the HTML section of the code; <body ng-controller ...

Tips for choosing the injected HTML's List Element (li) while ensuring it remains concealed

How do I hide the list item with iconsrc="/_layouts/15/images/delitem.gif" image when this div is injected by a first party and I am a third party trying to conceal it? $("<style> what should be inserted here ???? { display: none; } </style>") ...

Revamp the HTML page by automatically refreshing labels upon every Get request

My HTML webpage requires real-time updates for one or more labels. To achieve this, I have incorporated CSS and JS animations into the design. Currently, I am utilizing Flask to handle all the calls. I face a challenge where I need to consistently update ...

Exploring the functionality of jQuery's html() method through multiple interactions

I am currently experimenting with this demo. I'm investigating why the HTML content disappears after using the second button. Everything works fine as long as you only click on btn #from-content-1 or only on #from-content-2. But if you click on #from ...

What steps should I take to troubleshoot the 'TypeError: userId is not a function' error in my unban feature?

I am currently working on implementing an unban feature for my bot, however, I am encountering issues whenever I try to test the command (!unban <userId>). Instead of the expected outcome, I am faced with an error which is detailed below. This snipp ...

Unable to call component method after exporting with connect in React Redux

My React class component features a method that I would like to access later through the provider. Take a look at the class below: class ContactList extends Component { // props for contact renderContacts = () => { return // something }; ...

Display JSON information within a Bootstrap modal

Hi there! I'm just starting to learn about ajax, json, and modals. I have some data displayed in the console that I want to show in a modal pop-up. Specifically, when I click on the view request button for each employee, I should see their individual ...