Reputation: 375
I am using nodejs and express for api end points, I am using app.use
to handle a route, but it is not responding no matter what I do.
var express = require("express");
var mongoose = require('mongoose');
var path = require("path");
var favicon = require("serve-favicon");
var http = require('http');
var app = express();
var config = require('./conf/config');
var PORT = config.PORT;
mongoose.connect(config.MONGODB);
//route handlers
app.use('/', function(req, res) {
console.log("Hello");
});
var server = http.createServer(function(req, res) {
console.log("Request received", req.url);
});
server.listen(PORT);
console.log("Server running on port", PORT);
It should print hello on console whenever I request on root route i.e. /
but it's not doing anything.
Upvotes: 2
Views: 2424
Reputation: 707218
Your Express code is not correct. You are creating a plain web server, but that web server is not hooked up to Express in any way. If you aren't trying to create any special kind of server (like an https server), then you can just let Express create the server for you with app.listen(PORT)
and then it will create a server and hook itself up to that server.
I would suggest this:
var express = require("express");
var mongoose = require('mongoose');
var path = require("path");
var favicon = require("serve-favicon");
var app = express();
var config = require('./conf/config');
var PORT = config.PORT;
mongoose.connect(config.MONGODB);
//route handlers
app.get('/', function(req, res) {
console.log("Hello");
res.send("Hello");
});
app.listen(PORT);
console.log("Server running on port", PORT);
Note: I changed a couple other things too. I switched to app.get()
and I inserted a res.send()
since you need to always send some kind of response of the browser will just wait and wait for something to come back.
Upvotes: 3
Reputation: 8781
Try using app.get
instead of app.use
, as well. The latter is used for mounting sub-routes, using middleware etc. but not for actually configuring request handlers.
Upvotes: 0