【问题标题】:req.query is undefined in Next.js API routereq.query 在 Next.js API 路由中未定义
【发布时间】:2022-11-11 00:57:17
【问题描述】:

我正在尝试执行删除请求。我可以通过pages/api/people/[something].js 获取 API 路由。

这是我从浏览器控制台得到的响应。

删除 - http://localhost:3000/api/people/6348053cad300ba679e8449c - 500内部服务器错误)

6348053cad300ba679e8449c 来自应用程序启动时的 GET 请求。

例如,在 Next.js 文档中,API 路由 pages/api/post/[pid].js 具有以下代码:

export default function handler(req, res) {
  const { pid } = req.query
  res.end(Post: ${pid})
}

现在,对/api/post/abc 的请求将回复文本:Post: abc.

但是从我的 API 路由 pages/api/people/[something].js 来看,something 是未定义的。

const { something } = req.query

更新后的帖子:

反应组件

export default function DatabaseTableContent(props) {
  const id = props.item._id; // FROM A GET REQUEST

  const hide = useWindowSize(639);
  const [deletePeople] = useDeletePeopleMutation();

  async function deleteHandler() {
    await deletePeople(id);
  }
  return <Somecodes />;
}

apiSlice.js

export const apiSlice = createApi({
  // reducerPath: "api",
  baseQuery: fetchBaseQuery({ baseUrl: url }),
  tagTypes: ["People"],
  endpoints: (builder) => ({
    getPeople: builder.query({
      query: (people_id) => `/api/people/${people_id}`,
      providesTags: ["People"],
    }),
    
    deletePeople: builder.mutation({
      query: (studentInfo) => ({
        url: `api/people/people-data/student-info/${studentInfo}`,
        method: "DELETE",
        headers: {
          accept: "application/json",
        },
      }),
      invalidatesTags: ["People"],
    }),
  }),
});

export const {
  useGetPeopleQuery,
  useDeletePeopleMutation,
} = apiSlice;

页面/api/people/people-data/student-info/[studentInfo].js

import { ObjectId, MongoClient } from "mongodb";

async function handler(res, req) {
  const { studentInfo } = req.query; // the code stops here because "studentInfo" is undefined
  const client = await MongoClient.connect(process.env.MONGODB_URI.toString());
  const db = client.db("people-info");

  if (req.method === "DELETE") {
    try {
      const deleteData = await db
        .collection("student_info")
        .deleteOne({ _id: ObjectId(studentInfo) });

      const result = await res.json(deleteData);
      client.close();
    } catch (error) {
      return res.status(500).json({ message: error });
    }
  }
}

export default handler;

【问题讨论】:

  • 这些不是此 url http://localhost:3000/api/people/6348053cad300ba679e8449c 中的查询参数

标签: javascript reactjs next.js


【解决方案1】:

传递给handler 函数的参数顺序需要颠倒。

对于 NextJS API 路由,req 是传递给处理程序的第一个参数,res 是第二个参数。

NextJS 文档中的示例 handler 函数:

export default function handler(req, res) {
  res.status(200).json({ name: 'John Doe' })
}

【讨论】:

    猜你喜欢
    • 2020-08-12
    • 1970-01-01
    • 2021-07-04
    • 2021-12-09
    • 2021-06-21
    • 2020-05-19
    • 2020-06-06
    • 2023-04-01
    • 2016-11-22
    相关资源
    最近更新 更多