Почему Middleware не работает в Express JS - PullRequest
0 голосов
/ 18 сентября 2018

Я пытаюсь выучить промежуточное программное обеспечение в 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...');
})

Я получаю Server started on port 3000.., когда я запускаю на cmd и получаю "страница не работает" на localhost:3000

Отредактировано

Iполучил

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 голосов
/ 18 сентября 2018

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

0 голосов
/ 18 сентября 2018

Причина, по которой вы получаете сообщение "страница не работает", заключается в том, что ваше приложение не отвечает ни на один полученный запрос.

Вам нужно раскомментировать res.send('Hello World'); в app.get('/', ...). После этого ваш код работает отлично.

Обратите внимание, однако, что в структуре вашего кода ваше промежуточное программное обеспечение app.use(...) называется до , и вы получаете основную логику для маршрута (app.get(...)), в отличие от того, что указано вашим console.log звонки.

...