Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/api/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
导入API路由_Api_Fetch_Next.js - Fatal编程技术网

导入API路由

导入API路由,api,fetch,next.js,Api,Fetch,Next.js,我应该如何将其重写为函数? 我正在使用Next.JS构建一个工具&使用他们的api端点与MongoDB交互。 NextJS网站上说: 注意:不应使用fetch()在应用程序中调用API路由。相反,直接导入API路由并自己调用其函数。对于这种方法,您可能需要稍微重构代码。 从外部API获取是可以的 我应该如何重构代码以适应这种方法 import handler from '../../middleware/common_middleware'; handler.get(async (req,

我应该如何将其重写为函数? 我正在使用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;

在这里查看NextJS文档:

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

您可能应该有这样一个结构:

导出默认异步(req,res)=>{
试一试{
让query=req.query;
让queryName=Object.values(查询)[0];
//使用模块进行修改以查询数据库
让doc=wait req.db.collection(“志愿者”).find({u id:queryName}).toArray();
res.statusCode=201;
res.setHeader('Content-Type','application/json');
res.end(JSON.stringify({状态:'success',数据:doc});
}
抓住{
res.statusCode=400
res.setHeader('Content-Type','application/json');
res.end(JSON.stringify({status:'error',data:'配置文件不存在'}))
}
}

没有尝试过,但希望它能提供一个想法。

在这里查看NextJS文档:

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

您可能应该有这样一个结构:

导出默认异步(req,res)=>{
试一试{
让query=req.query;
让queryName=Object.values(查询)[0];
//使用模块进行修改以查询数据库
让doc=wait req.db.collection(“志愿者”).find({u id:queryName}).toArray();
res.statusCode=201;
res.setHeader('Content-Type','application/json');
res.end(JSON.stringify({状态:'success',数据:doc});
}
抓住{
res.statusCode=400
res.setHeader('Content-Type','application/json');
res.end(JSON.stringify({status:'error',data:'配置文件不存在'}))
}
}

我没有尝试,但希望它能提供一个想法。

谢谢!我正在从中间件函数导入处理程序,但是,我将如何在处理程序上运行该函数?谢谢!我正在从中间件函数导入处理程序,但是,我将如何在处理程序上运行该函数?