如何使用查询字符串在 Next.js 中创建 api 终点

How can I create api end point in Next.js with query string

我需要使用 Next.js 创建以下 api 端点:

/api/products/[name]?keyword=${anykeyword}.

我知道我需要在 index.js 的 pages/api/products/[name] 目录中创建它。但是我怎样才能访问 keyword.

req.query 只包含 name.

以下是我的代码:

    import { connectToDatabase } from "../../../../util/mongodb";
    import validate from "../../../../validation/product";
    //capitalize first letter only to avoid errors
    import capitalize from "lodash.capitalize";

    export default async function productsHandler(req, res) {
    const {
      query: { name, keyword }, // here i cannot access keyword//
      method,
    } = req,
    Name = capitalize(name),
    { db } = await connectToDatabase(),
    searchCriteria = keyword ? keyword : "price";

  switch (method) {
    case "GET":
      // @route GET api/products/[name]
      // @desc get products of [name] from data base
      // @access public
      {
        const products = await db
          .collection("products")
          .find({ category: Name })
          .sort({ [searchCriteria]: 1 })
          .toArray();

        if (!products.length)
          return res.status(404).json({ error: "no such category" });

        res.status(200).json(products);
      }

      break;

这可能与请求从客户端发送到服务器端的方式有关。您可能需要修改它。我刚刚使用 Postman 尝试了这个例子,它正确地解析了参数:

import { NextApiRequest, NextApiResponse } from "next";

export default async (request: NextApiRequest, response: NextApiResponse) => {
  const {
    query: { name, keyword },
    method,
  } = request;
  console.log(name, keyword, method);

  // do nothing fancy and simply return a string concatenation
  return response.status(200).json({ query: name + " " + keyword });
};

邮递员: