为什么中间件不能在快速js中工作

问题描述 投票:2回答:2

我试图在快递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仍然无法正常工作

node.js express middleware
2个回答
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发送获取请求


3
投票

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

你需要在res.send('Hello World');中取消注释那个app.get('/', ...)。之后,您的代码完美无缺。

但请注意,在代码结构中,在到达路径的主逻辑(app.use(...))之前调用中间件app.get(...),这与console.log调用所指示的相反。

© www.soinside.com 2019 - 2024. All rights reserved.