我想從前端的 nextjs 服務器獲取資料,但是 fetch() 之后的代碼在 onSubmit() 函式中不起作用。這是/測驗頁面
頁面/測驗
const onSubmit = (data) => {
console.log("________");
users.map(async (user, index) => {
if (data.email === user.email) {
if (data.password === user.password) {
console.log("hi");
const data = await fetch("http://localhost:3000/api/test");
// after the fetch, this code does not run
console.log("back-end is: ", data);
}
}
});
};
這是我在/api/test中的代碼
export default async function student_method(req, res) {
return console.log("get in server");
}
所以請問是什么問題??
我正在嘗試獲取資料庫中的資料,因此我們需要使用 fetch() 方法,但 fetch() 成功運行,但 fetch() 之后的代碼不起作用
uj5u.com熱心網友回復:
我認為問題是return在服務器端使用陳述句。NextJS 在res您在服務器端函式中接收到的物件中提供輔助方法。
嘗試這樣的事情:
res.status(200).send("get in server");
有關詳細資訊,請參見此處:API 路由:回應助手
uj5u.com熱心網友回復:
const data = await fetch("http://localhost:3000/api/test");
問題是那條線。你在那里等待一個Promise解決,但是如果你看到你的api/test你只回傳一個日志。
請嘗試回傳一個 Promise。
uj5u.com熱心網友回復:
該代碼現在不作業,因為您正在等待服務器回應,但您沒有從服務器發送任何內容。
您應該像這樣向客戶端發送回應:
export default async function student_method(req, res) {
/* status code 200 or any other status codes */
res.status(200).send("get in server");
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/536976.html
上一篇:reactnative(型別腳本):在平面串列中選擇父子復選框
下一篇:useRef()不重繪值
