'How to redirect to another page Reactjs/nextjs sending data with post

How can I send data using post I got this

router.push({
            pathname: "/investigacion-detalle",
            query: { data: JSON.stringify(salida),},
        });

but all it's sended on the url, I want to use a redirect post, to send all data and make the redirection, but I don't know how to make that, I try making a fetch but that only give me a response from the page not the redirect

The redirect Page:

import React,{useEffect} from "react";
import { useRouter } from 'next/router'
import { withRouter } from 'next/router'
const InvestigacionDetalle = (props)=>{
  const router = useRouter()
  const handleURL = (e)=>{
    router.push('/investigacion');
  };
  useEffect(()=>{
    console.log(props.router.query.data);
  },[])
return(
    <div>
  <div>Investigacion page</div>
  <button onClick={handleURL}>test</button>
  </div>
  );
}
export default withRouter(InvestigacionDetalle);


Solution 1:[1]

I guess you mean making a POST request and then redirecting to another page.

You could create an async function to make the post request and then, once the request is completed, redirect to another page. For example, using axios:

const postRequest = async () => {
 try {
  const response = await axios.post(url);
  return response;
  
} catch(error) {
 throw new Error(error);
  }
}

Then you could call this function to set a state with the response for example, doing your redirect after:

postRequest().then((response) => {
//Do something with the response
}).then(() => {
router.push("/to-your-page")
}).catch((error) => {
//Do something with the error
})

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 ivanatias