NextJS Send/Submit Post Request

NextJS Send/Submit Post Request

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.