【问题标题】:How to get / and /:someText in node.js?如何在 node.js 中获取 / 和 /:someText?
【发布时间】:2018-03-15 19:22:26
【问题描述】:
 app.get('/',function(req,res,next){
       app.use(express.static(html file);
       next();
    });

app.get('/:someText',function(req,res){
var x = req.params.someText;
res.send(x);
});

我得到了两者的输出,但没有得到 express.static(html) 文件的 CSS。

【问题讨论】:

    标签: node.js express


    【解决方案1】:

    正如我从您缺少的代码中看到的那样,在 get / 中发送。

    app.get('/',function(req,res,next){
       //something
       //in here add res.send() and all OK.
    });
    

    选中此项以了解下一步的用途。

    What is the parameter "next" used for in Express?

    【讨论】:

      【解决方案2】:

      您使用express.static 的方式不正确。您不应该将单个文件传递给它以返回,即sendFileexpress.static 用于提供整个目录,应在 get 处理程序之外调用。

      例如,这将在 URL 的根目录提供一个名为 public 的目录。任何未找到的文件请求都将通过中间件/路由器链传递到下一个处理程序:

      app.use(express.static(path.join(__dirname, 'public')));
      

      重要的是,这应该出现在您对 app.getapp.post 等的调用之前,而不是在处理程序中。

      因此,如果您在public/myfile.html 有一个文件,该文件将在http://localhost:3000/myfile.html 提供,我假设您的服务器位于localhost:3000。如果您想在 URL 中添加额外的路径部分,例如http://localhost:3000/stat/myfile.html 那将是:

      app.use('/stat', express.static(path.join(__dirname, 'public')));
      

      如果你想提供一个文件,那么你可以使用sendFile,有点像这样:

      app.get('/myfile.html', function(req, res) {
          res.sendFile(path.join(__dirname, '/myfile.html'));
      });
      

      请注意,这是挑选出一个特定文件,因此任何资源(如 CSS)都需要单独处理。如果 HTML、CSS 等都在同一个文件夹中,则使用 express.static 来提供整个目录是有意义的。

      还值得注意的是,express.static 有一个名为 index 的设置,如果对“/”的请求进入,则默认提供名为 index.html 的文件。

      进一步阅读:

      【讨论】:

        猜你喜欢
        • 2022-11-25
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-11-27
        • 1970-01-01
        相关资源
        最近更新 更多