【问题标题】:Importing API Routes导入 API 路由
【发布时间】:2021-01-02 12:47:43
【问题描述】:

我应该如何将它重写为一个函数? 我正在使用 Next.JS 构建一个工具,并使用他们的 api 端点与 MongoDB 进行交互。 NextJS 网站说:

注意:您不应该使用 fetch() 在您的应用程序中调用 API 路由。相反,直接导入 API 路由并自己调用它的函数。您可能需要针对这种方法稍微重构您的代码。 从外部 API 获取很好!

我应该如何重构我的代码以适应这种方法?

import handler from '../../middleware/common_middleware';


handler.get(async (req, res) => {
    try {
        let query = req.query;
        let queryName = Object.values(query)[0];
        let doc = await req.db.collection("Volunteers").find({"_id": queryName}).toArray();
        res.status(201).json(doc);
    }
    catch {
        res.status(400).send("The profile doesn't exist.");
    }
});

export default handler;

【问题讨论】:

    标签: api fetch next.js


    【解决方案1】:

    在这里查看 NextJS 文档:

    https://nextjs.org/docs/api-routes/introduction https://github.com/vercel/next.js/blob/canary/examples/api-routes-rest/pages/api/users.js

    你可能应该有这样的结构:

    export default async (req, res) => {
        try {
            let query = req.query;
            let queryName = Object.values(query)[0];
            // modify with the module to make query to db
            let doc = await req.db.collection("Volunteers").find({"_id": queryName}).toArray();
            res.statusCode = 201;
            res.setHeader('Content-Type', 'application/json');
            res.end(JSON.stringify({status:'success', data: doc});
        }
        catch {
            res.statusCode = 400
            res.setHeader('Content-Type', 'application/json');
            res.end(JSON.stringify({status: 'error', data: 'The profile doesn't exist.' }))
        }
    
    }
    

    没试过,希望能给个思路。

    【讨论】:

    • 谢谢!我正在从中间件函数中导入处理程序,但是,我将如何在处理程序上运行该函数?
    猜你喜欢
    • 2022-11-01
    • 2021-01-10
    • 1970-01-01
    • 2020-07-30
    • 2019-10-13
    • 1970-01-01
    • 2012-07-28
    • 2017-05-30
    • 1970-01-01
    相关资源
    最近更新 更多