为什么中间件不能在Express JS中工作

时间:2018-09-18 04:03:30

标签: node.js express middleware

我正在尝试学习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上运行时,我得到Server started on port 3000..,而在localhost: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仍然无法正常工作

2 个答案:

答案 0 :(得分:3)

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

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

但是请注意,在代码的结构中,将中间件app.use(...)称为之前,然后您会转到路由的主要逻辑(app.get(...)),相反到您的console.log通话所指示的内容。

答案 1 :(得分:1)

enter image description here

   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