简体   繁体   中英

Express Does app.js get ran on every request?

I am building an express server with pretty standard stuff. I've been unable to get express.router() to execute my routes correctly, which has caused me to dig deeper into what is actually happening when a page is requested from a server running an express app.

console.log('App.JS has ran!');
var http = require('http');
var express = require('express');
var app = express();
var server = http.createServer(app);
var mongoose = require('mongoose');
mongoose.connect('mongodb://52.27.161.16');
mongoose.connection.on("connect",function(err) { 
  if (err) throw err;
  console.log('hello found!');
});
var bodyParser = require('body-parser');
app.use(bodyParser.json());
var router = express.Router();
router.get('/hi'), function (req, res) {
    res.send('/hi route response');
};
router.get('/', function(req, res) {
  res.send('default route reached');
});
app.use('*', router);
server.listen(config.server.listenPort);

Pretty standard stuff—but for some reason whenever I navigate to localhost:port/hi I am only getting the res from the / path, ie router.get('/', function{} (res.send('default route reached'));

So I've become more interested in what's happening behind the scenes. I've noticed that the server only logs to the terminal the output not related to the bodyParser on the first request. Ie, the console.log at the top of the file only gets ran when the application is started, and never after, though bodyParser correctly logs requests for each request instance.

What's going on exactly when a request is made to the server? Is the app object and route cached and being served? Why is app.js not being re-evaluated on each request? Is only the router object responsible for sending requests over?

It would be helpful to know this, to figure out why my router is not responding with the correct route.

Thanks a bunch!

The app object is the express application that you are creating. It is basically a wrapper for the express module which includes all the express functionalities. It basically reduces the code that you requires to handle requests made to the server, rendering the HTML views, registering a template engine etc. This app object is passed to the server object that you are creating and the server continuously listens to requests in the port that you have configured. So, when the server is running, the app object is initiated only once and the requests to the server are handled by the node event loop.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM