javascript - Unable to map routes file with ExpressJS Router -
I am reading an introduction book about ExpressJS and unfortunately they are using Express 3.x. I'm trying to update my code to express example 4.x. Here's an example:
route / index.js app.js Here, However, when going to If I completely use the router class (and remove And that will work. How do I load my outer path with the router class? In Express 4, you create your own path using the router. Say, your route / index.js and path / foo.js, they will see something like this: In your main server file, you can use these router app, you can attach them to different places. You can also make router to attach the router to the router (for example, the user / user-id / picture / image-id type route). and now you should be able to get GET / and GET / foo / bar. For a little more technical accuracy, you need middleware only on routes. You can make this per router, or per-end point. It is usually good to do, but in some cases it may also be very important, e.g. Handling file uploads
export.index = function (req, res) {res.send (' Welcome'); };
var express = expected ('express'); Var http = Required ('http'); Var app = express (); // Load the root handlers requires different routes ('./routes'); // router middleware explicitly add app.use (app.router); // roots app.get ('/', routes.index); Http.createServer (app) .listen (3000, function () {console.log ('app start');});
app.router dislikes and the node throws an error about it I updated the code:
Var http = Required ('http'); Var Express = Required ('Express'); Var app = express (); Var bodyParser = is required ('body-parser'); Var router = express.routor (); Var routes are required ('./routes'); Router.get ('/', routes.inx); App.use (bodyParser.urlencoded ({extended: true})); App.use (bodyParser.json ()); Http.createServer (app) .listen (3000, function () {console.log ('Express app start');});
localhost: 3000 , I see this error in the browser:
can not be found /
app.router) ), then just do this I can:
app.get ('/', routes .indack);
// path / index.js var router = Required ('Express'). Router (); Router.get ('/', function (rik, ridge) {res.send ('hello!');}); Module.exports = Router; Requires the
// path / foo.js var router = ('Express'). Router (); Router.get ('/ bar', function (rik, ridge) {res.send ('foobar');}); Module.exports = Router;
// server.js var http = require ('http'); Var Express = Required ('Express'); Var app = express (); Var bodyParser = is required ('body-parser'); App.use ('/', is required ('. / Route / index')); App.use (bodyParser.urlencoded ({extended: true})); App.use (bodyParser.json ()); App.use ('/ foo', Required ('./routes / foo')); App.listen (3000);
router.use (bodyParser.json ()); // router.route ('/ baz') .use (bodyParser.json ()) .post (function (rik, ridge) {res.status (201) .json (req.body);});
Comments
Post a Comment