Jav*_*goa 0 api post request node.js next.js
我正在 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>
}
Run Code Online (Sandbox Code Playgroud)
但是在运行next dev
或后build && start
,当我单击发布帖子的按钮时,我收到错误:TypeError: Failed to fetch
指向该fetch()
函数。
当我向其他网页发送 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
Run Code Online (Sandbox Code Playgroud)