0

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!

1 Answer 1

6

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
2
  • That was part of the problem. It also had a cors policy issue I solved afterwards. Thank you :) Commented Apr 20, 2022 at 13:48
  • How did you resolve the cors policy issue @JavierBurgoa , I seem to be having the same.
    – xodeeq
    Commented Apr 18, 2023 at 6:10

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.