Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/node.js/39.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
Node.js 函数为';正在使用RESTAPI在节点Js中调用t_Node.js_Rest - Fatal编程技术网

Node.js 函数为';正在使用RESTAPI在节点Js中调用t

Node.js 函数为';正在使用RESTAPI在节点Js中调用t,node.js,rest,Node.js,Rest,我正在NodeJS中编写一段代码,它使用Mustach作为html模板和RESTAPI作为后端 这是我的代码,不起作用 function setupRoutes(app) { const base = app.locals.base; app.get(`${base}/search.html`,doSearchContent(app)); app.get(`${base}/:name`,doGetContent(app)); } function doSearchConte

我正在NodeJS中编写一段代码,它使用Mustach作为html模板和RESTAPI作为后端

这是我的代码,不起作用

function setupRoutes(app) {
 const base = app.locals.base;

app.get(`${base}/search.html`,doSearchContent(app));   
app.get(`${base}/:name`,doGetContent(app));     
}

function doSearchContent(app) {
  return async function(req, res) {
    console.log("here");
  }; };
当我运行程序并转到base/search.html时。它从不调用doSearchContent方法

你知道我为什么以及如何解决这个问题吗


编辑:doGetContent按预期工作。当我运行search.html时,它不会

快速路径应该以前导斜杠开始。除此之外,请更改您的路线:

...
app.get(`/${base}/search.html`,doSearchContent(app));   
app.get(`/${base}/:name`,doGetContent(app));
...
Express将http请求的路径与为所有路由提供的“路径”相匹配,以决定必须调用哪些路由。由于http路径总是以斜线开头,因此路由还必须指定要匹配的路径

这些线

app.get(`${base}/search.html`,doSearchContent(app));   
app.get(`${base}/:name`,doGetContent(app)); 
你的工作没有你想象的那样好。在快速路由中,我们不直接调用函数。相反,我们要么传递要调用的回调函数的名称,该函数接收
req
res
参数,要么传递匿名回调。在您的情况下,可能是这样的:

app.get(`${base}/search.html`,(req, res) => {
    console.log("It's alive!");
    doSearchContent(app);
});   
app.get(`${base}/:name`, (req, res) => { 
    doGetContent(app)
}); 

快速路径应以前导斜杠开始


这不是真的

您是否添加了search.html文件或使用模板来构建html

确保调用的是模板,而不是html文件


除此之外,您的代码看起来不错,应该可以正常工作

我尝试使用此方法。在OP的示例中,doSearchContent返回一个函数,所以它仍然可以工作。@即使在理想情况下,它也可以工作,这就是为什么我不确定为什么它不能工作的原因working@Evert是的,这确实是一个疏忽@Mike Ross在本例中,您可以使用
app.use('*',(req,res,next)=>{console.log(req.originalUrl);next()})
预先设置路由,以检查您的实际路由是否匹配
${base}/search.html
@antopastukhov我尝试过,即使没有为搜索打印出来。html页面您可以分享您使用的框架吗?你正在使用某种路由器。我添加了一个html文件。谢谢我制作了一个模板文件,现在可以使用了:)