簡體   English   中英

從客戶端發送 NEXTjs 中的 POST 請求

[英]Sending a POST request in NEXTjs from client side

我正在 NEXTjs 中開發一個 web。 我需要它在用戶單擊按鈕時觸發 POST 請求。

我在localhost:55331上有一個處理請求的節點應用程序(我測試過)。

NEXTjs 應用程序示例:

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>
}

但是在運行next devbuild && start ,當我單擊發布帖子的按鈕時,出現錯誤: TypeError: Failed to fetch poitning at the fetch() function。

當我向其他網頁發送 POST 請求時也會發生這種情況,當然我永遠不會得到回應。

您是否知道如何從客戶端發送發布請求並獲得響應

干杯!

您應該將函數放在Page組件中。 來自getStaticProps的函數在組件中不可訪問。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM