Home > Software engineering >  Sending a POST request in NEXTjs from client side
Sending a POST request in NEXTjs from client side

Time:04-21

I am developing a web in NEXTjs. I need it to trigger a POST request when the user clicks a button.

I have a node app on localhost:55331 that handles the request (I tested it).

A sample of the NEXTjs app:

export const getStaticProps = async (context) => {
  
// Here I am just creating the function that will be triggered when clicking a button

  async function postData(url = '', data = {}) {
    
    const response = await fetch(url, {
        method: 'POST',
        mode: 'cors',
        .
        .
        .
        body: JSON.stringify(data)
    });
    
    const json = await response.json();
    return json
 }
      
  

  async function getresponse (data){
    postData('http://localhost:55331/', data)
    .then(res => {
            alert(res.body)
        })
   }
}




// This is the static page, the client side, where the function will be triggered
const Page = () =>{

    return(
        
        <div>
           <button onClick {()=>getresponse({'data'})}>Send POST</button>                       
        </div>
}

But after running next dev or build && start, when I click the button that makes the post I get the error: TypeError: Failed to fetch poitning at the fetch() function.

This happens also when I send a POST request to other webpages, and of course I never get a response.

Do you have any idea of how can I send a post request from the client side and get a response?

Cheers!

CodePudding user response:

You should put your functions inside Page component. Functions from getStaticProps are not accessible in the component.

const Page = () =>{
 async function postData(url = '', data = {}) {
    
    const response = await fetch(url, {
        method: 'POST',
        mode: 'cors',
        .
        .
        .
        body: JSON.stringify(data)
    });
    
    const json = await response.json();
    return json
 }
      
  async function getresponse (data){
    postData('http://localhost:55331/', data)
    .then(res => {
            alert(res.body)
        })
   }
  }

    return(
        
        <div>
           <button onClick {()=>getresponse({'data'})}>Send POST</button>                       
        </div>
}

export default Page
  • Related