"When testing with an API client, NextJS 13 successfully returns a response, however, the same response

Having trouble getting a clear answer on something really simple.

I've created an API route:

// /api/test/route.js
export async function GET(request, response) {
  console.log("requested");
  return NextResponse.json({ my: "data" });
}

On the other hand, I have a component that sends a request to the endpoint when a button is clicked (I included headers for troubleshooting purposes):

// /components/client/test.js
"use client";

export default function ExampleClientComponent({children}) {

  async function handleClick() {
    let data = await fetch("http://localhost:3000/api/test", {
      method: "GET",
      headers: {
        "Content-Type": "application/json",
        Accept: "application/json",
      },
    });
    console.log("data", data);
  }
   
  return (
    <>
      <button onClick={handleClick}>Go</button>
    </>
  );
}

Upon clicking the button, the console confirms the request was sent and I receive a 200 response in the browser. The body is a ReadableStream, which seems to be the default response for HTTP Responses. However, I expected NextResponse to return the response as JSON.

Response
body: ReadableStream {locked: false}
bodyUsed: false
headers: Headers {append: function, delete: function, get: function, has: function, set: function, …}
ok: true
redirected: false
status: 200
statusText: "OK"
type: "basic"
url: "http://localhost:3000/api/test"

Testing the endpoint directly gives me a JSON body

HTTP/1.1 200 OK
connection: close
content-encoding: gzip
content-type: application/json
date: Tue, 25 Jul 2023 23:15:42 GMT
transfer-encoding: chunked
vary: RSC, Next-Router-State-Tree, Next-Router-Prefetch, Accept-Encoding

{
    "my": "data"
}

What could possibly be causing this? The tutorials and documentation I've reviewed (mostly regarding POST requests) indicate this should work. All I expect is to receive a response with a JSON body.

Answer №1

When using the fetch() method, a Promise is returned. To access the response from the endpoint, follow these steps.

const response = await fetch("http://localhost:3000/api/test", {
      method: "GET",
      headers: {
        "Content-Type": "application/json",
        Accept: "application/json",
      },
    });
const data = await response.json();
console.log(data);

To learn more about this topic, visit the following link to the documentation.
https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch

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

Display and conceal multiple div elements using a timer

Currently, I am working on creating a message box that will display active messages one by one from a MySQL table. The challenge is that the number of divs needed can vary depending on the number of active messages in my database. Using an ajax timer and P ...

The Contact.php page has the ability to send emails, however, the content of the

I have recently added a contact form to my website using a template. Although I am able to send and receive email messages successfully, I am facing an issue where the actual message content entered by users is not being received in my Inbox. Here is a sc ...

Is it possible to add a class to a child element deep within the component hierarchy while using TransitionGroup/CSSTransition in React?

I currently have a setup like this: Parent Component: <TransitionGroup> { items.map((child, index) => { // do something return ( <CSSTransition key={index} nodeRef={items.nodeRef} timeout={1000} classNames={'item ...

What steps should I take to host a Node.js application on a subdomain using an apache2 VPS?

Currently, I have a Node.js application that I would like to host on a subdomain using my VPS. The VPS is running apache2 and the Node.js app utilizes Express. Despite trying both Phusion and following this tutorial, I have been unsuccessful in getting i ...

retrieve data for chart from an AJAX request

I am looking to create a chart using amCharts and I have received some values from the server through an ajax call. Now, I need help in utilizing this data for my chart. Can anyone guide me on how to achieve this? var chart = am4core.create("chartdiv& ...

"Automatically close the fancybox once the form is confirmed in the AJAX success

Having an issue with closing my fancybox after submitting the registration form on my website. I am using the CMS Pro system.... Here is how I display the fancybox with the form: submitHandler: function(form) { var str = $("#subscriber_application"). ...

There is a possibility of encountering an endless update loop in the watcher when utilizing the expression "tabs" error in vue

My code includes a watcher on tabs to prevent them from changing based on the values of the edit. If edit is false, then go to the next tab; otherwise, prevent the change. However, when I try to click on the tab heading to change the tab, I encounter an er ...

Can you explain the distinction between using single and double quotes in my JavaScript and CSS code?

Is there a significant distinction between using single or double quotes in JS and CSS? Does it depend on personal preference, or are there certain instances where one is preferred over the other? In W3Schools, they employ single quotes for url('&apo ...

Retrieving data using Next.js 'catch-all' routes

Using Next.js 10, you now have the ability to create a catch all route that looks something like this: [...id].tsx. This enables the development of dynamic pages that can match paths such as /example, /example/new, and /example/new/latest. However, one is ...

What are the steps for implementing CORS?

I recently attempted to set up Ajax calls and stumbled upon the following code snippet: <!DOCTYPE html> <html> <body> <p id="demo">Let AJAX update this text.</p> <button type="button" onclick="loadDoc()">Updat ...

Is it possible to load Javascript using AJAX with jQuery?

So I have this JavaScript code that I insert into a webpage using the following: <script type="text/javascript" src="http://ext.nicovideo.jp/thumb_watch/sm13154955?w=640&h=395"></script> It basically places an object/embed code into the w ...

Discover the Magic Trick: Automatically Dismissing Alerts with Twitter Bootstrap

I'm currently utilizing the amazing Twitter Bootstrap CSS framework for my project. When it comes to displaying messages to users, I am using the alerts JavaScript JS and CSS. For those curious, you can find more information about it here: http://get ...

Ensure that the div remains within the viewport

<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Tit ...

What is the process for exporting all sub-module types into a custom namespace?

When we import all types from a module using a custom-namespace, it appears to work smoothly, for example: import * as MyCustomNamespace from './my-sub-module' We are also able to export all types from a module without creating a new namespace, ...

When the video message bubble is touched within the chat app, a video player will automatically pop up (using React Native)

Currently, I am developing a chat app in React Native that can handle the sending and receiving of video files. However, I am facing challenges with activating the video player when a user presses on the video message inside the chat bubble. Despite my att ...

Is there a way to verify HTML binding prior to setting up an AngularJS directive?

On a page where I utilized a custom select-box directive to display the Month, certain arguments are required by the directive: <custom-select-box id="month" model="month" model-required model-name="month" options="month.value ...

Accessing JavaScript cookie within .htaccess file to establish redirection parameters according to cookie content

Is there a way to modify the rules within my .htaccess file so that it can properly read a user-side cookie and redirect based on its content? The scenario is this: I have a cookie called userstate which contains an abbreviation of US states, such as AL ( ...

The functioning of JavaScript's ajax capabilities

Need some help with a coding issue I'm facing. Can anyone provide suggestions for improving my code? I've come across a situation where the table is not updating when using a certain piece of code. However, upon further inspection, I found that ...

"Let's delve into the world of dynamic variables and Javascript once

As a newcomer to JS, I've scoured countless posts for solutions, but nothing seems to work for me. The issue arises when trying to abstract the code to handle all variables rather than just explicitly expressed values. I am open to alternative method ...

Verify the presence of a GET parameter in the URL

Working on a simple log in form for my website using Jade and ExpressJS. Everything is functioning correctly, except for one issue - handling incorrect log in details. When users input wrong information, they are redirected back to the log in page with a p ...