Loading episodes…
0:00 0:00

NextJS Send/Submit Post Request

00:00
BACK TO HOME

NextJS Send/Submit Post Request

10xTeam September 28, 2023 3 min read

Today, it’s fairly usual for our web applications to call data from a number of external APIs in a microservice architecture. You may have a single API that manages orders, alerts, or other CRUD tasks.

You’ll discover how to use NextJS to make/send or submit a POST request to an external API in this tutorial.

We’ll demonstrate sending a post request to an external api in this tutorial.

import Head from "next/head";
import { useState } from "react";

export default function SendPostRequestExample() {
  const [item, setItem] = useState({item:''});
  const [data, setData] = useState();

  const onClick = async (e) => {
    e.preventDefault();

    await fetch("/api/endpoint", {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
      },
      body: JSON.stringify(todo),
    })
      .then((res) => res.json())
      .then((data) => setData(data.todo));
  };
  return (
    <div>
      <Head>
        <title> Next.js 13 send/submit post to external API</title>
      </Head>

      <form
        onSubmit={onClick}
      >
        <label htmlFor="Last name">Item name</label>
        <input
          onChange={() => {
            setItem({item:event.target.value});
          }}
        ></input>

        <button
          type="submit"
        >
          <>Submit</>
        </button>
      </form>
      <div>{data ? "item is : " + data : ""}</div>
    </div>
  );
}

}

The form will send data to an outside API.

In order for our back end to comprehend the request content, we converted our JS object into a json using the json.stringify function before using fetch to submit the request to the external API.


Join the 10xdev Community

Subscribe and get 8+ free PDFs that contain detailed roadmaps with recommended learning periods for each programming language or field, along with links to free resources such as books, YouTube tutorials, and courses with certificates.

Audio Interrupted

We lost the audio stream. Retry with shorter sentences?