【问题标题】:NEXTJS - fetching data from the serverNEXTJS - 从服务器获取数据
【发布时间】:2022-11-21 03:27:11
【问题描述】:

我想从前端的 nextjs 服务器获取数据,但是 fetch() 之后的代码在 onSubmit() 函数中不起作用。 这里是/test

页面/测试

  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() 之后的代码不起作用

【问题讨论】:

    标签: javascript reactjs next.js fetch


    【解决方案1】:

    我认为问题出在服务器端使用 return 语句。 NextJS 在您在服务器端函数中收到的 res 对象中提供辅助方法。

    尝试这样的事情:

    res.status(200).send("get in server");
    

    详情看这里:API Routes: Response Helpers

    【讨论】:

      【解决方案2】:
      const data = await fetch("http://localhost:3000/api/test");
      

      问题是那条线。你在那里等着承诺解决,但如果你看到你接口/测试你只返回一个日志。

      请尝试返回一个 Promise。

      【讨论】:

      • 我相信 async 关键字会始终将结果包装在对您的承诺中。
      【解决方案3】:

      该代码现在不起作用,因为您正在等待服务器响应,但您没有从服务器发送任何内容。

      您应该像这样向客户端发送响应:

      export default async function student_method(req, res) {
        /* status code 200 or any other status codes */
        res.status(200).send("get in server");
      }
      

      【讨论】:

        猜你喜欢
        • 2021-10-28
        • 1970-01-01
        • 2021-10-21
        • 2017-11-20
        • 1970-01-01
        • 1970-01-01
        • 2023-03-17
        • 1970-01-01
        • 2019-11-14
        相关资源
        最近更新 更多