Reputation: 1244
I'm trying to create a collection of microservices. The problem is, my routes don't seem to redirect to the right place.
Here is my index.js file:
var express = require("express");
var app = express();
var port = process.env.PORT || 3000;
var timestamp = require("./routes/timestamp");
app.listen(port, function(){
console.log("Listening on port " + port);
});
app.get("/", function(req, res){
res.writeHead(200, {"Content-Type": "text/html"});
res.end("Hi! This is a collection of microservices. <a href='https://github.com/Humad/timestamp-microservice'>See instructions here.</a>");
});
app.get("/timestamp", timestamp);
And here is my 'timestamp' file:
var express = require('express');
var router = express.Router();
var moment = require("moment");
router.get("/", function(req, res){
res.send("Hello world!");
});
router.get("/:date", function(req, res){
var newDate = req.params.date;
var natural = moment.utc(newDate, "MMMM D, YYYY", true);
var unix = moment.utc(newDate, "X", true);
if (natural.isValid() || unix.isValid()) {
if (natural.isValid()) {
newDate = natural;
} else {
newDate = unix;
}
res.json({unix: newDate.format("X"), natural: newDate.format("MMMM D, YYYY")});
} else {
res.json({unix: null, natural: null});
}
res.end();
});
module.exports = router;
Here is whats SUPPOSED to happen:
localhost/timestamp should give me "Hello World!" localhost/timestamp/someDate should give me a JSON file with the dates
But here is what actually happens:
localhost/timestamp gives me a JSON file with the dates localhost/timestamp/someDate gives me a Cannot GET error And the "Hello World" is never shown
Upvotes: 0
Views: 58
Reputation: 422
Change the line app.get("/timestamp", timestamp);
to app.use("/timestamp", timestamp);
.
I think you intended mounting the timestamp Router middleware on /timestamp
path, and not as a callback to a GET request which is what you are currently doing.
Upvotes: 3