【问题标题】:Why is Middleware not working in express js为什么中间件不能在 express js 中工作
【发布时间】:2018-09-18 04:03:30
【问题描述】:

我正在尝试学习 express js 中的中间件。任何人都可以在我失踪的地方提供帮助吗?这是我的代码

var express = require('express');
var bodyParser = require('body-parser');
var path = require('path');

var app = express();

app.use("/", function(req, res, next){
  console.log("this is my second output");
  next();
});

app.get('/', function(req,res){
  console.log("this is my first output");
//res.send('Hello World');
});

app.listen(3000, function(){
  console.log('Server started on port 3000...');
})

当我在 cmd 上运行并在 localhost:3000 上获得“页面不工作”时,我收到了 Server started on port 3000..

编辑

我明白了

Server started on port 3000...
this is my second output
this is my first output
this is my second output
this is my first output
this is my second output
this is my first output
this is my second output
this is my first output
this is my second output
this is my first output
this is my second output
this is my first output
this is my second output
this is my first output

过了一段时间。但是 localhost:3000 还是不行

【问题讨论】:

    标签: node.js express middleware


    【解决方案1】:

    您收到“页面不工作”消息的原因是您的应用程序没有响应它收到的任何请求。

    您需要在app.get('/', ...) 中取消注释res.send('Hello World');。之后,您的代码就可以正常工作了。

    但是,请注意,在您的代码结构中,您的中间件 app.use(...) 在您到达路由的主要逻辑 (app.get(...)) 之前被称为 ,这与您的console.log 电话。

    【讨论】:

      【解决方案2】:

         var express = require('express');
          var bodyParser = require('body-parser');
          var path = require('path');
      
          var app = express();
          // use this middleware to pass all the requests
          app.use("/", function(req, res, next){
            console.log("this is my second output");
          // move to next middleware
            next();
          });
          //handle all the get requests to localhost:3000 url
          app.get('/', function(req,res){
            console.log("this is my first output");
          // send the response
          res.send('Hello World');
          // or you can send the response like this 
          // res.json(JSON.stringify({"success":"true"}));
          });
      
          app.listen(3000, function(){
            console.log('Server started on port 3000...');
          })
      

      http://localhost:3000发送获取请求

      【讨论】:

        猜你喜欢
        • 2016-11-20
        • 1970-01-01
        • 2022-11-30
        • 2018-01-02
        • 1970-01-01
        • 2021-09-08
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多