我正在用 NEXTjs 開發一個網路。當用戶單擊按鈕時,我需要它來觸發 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 devor之后build && start,當我單擊發布帖子的按鈕時,我得到了錯誤:TypeError: Failed to fetch
指向fetch()函式。
當我向其他網頁發送 POST 請求時也會發生這種情況,當然我從來沒有得到回應。
您知道如何從客戶端發送發布請求并獲得回應嗎?
干杯!
uj5u.com熱心網友回復:
你應該把你的函式放在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
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/460479.html
