【问题标题】:How can I create api end point in Next.js with query string如何使用查询字符串在 Next.js 中创建 api 端点
【发布时间】:2021-05-23 06:19:48
【问题描述】:

我需要使用 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;

【问题讨论】:

标签: reactjs api next.js query-string


【解决方案1】:

这可能与请求如何从客户端发送到服务器端有关。你可能需要修改它。我刚刚尝试了使用 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 });
};

邮递员:

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-02-24
    • 2021-10-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-08
    相关资源
    最近更新 更多