简体   繁体   中英

Sending a POST request in NEXTjs from client side

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!

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM