简体   繁体   中英

How to export routes in node.js and express?

My problem is not in the question totally, but it's in the same page. So I exported a route to my main app.js file but the my post route isn't working. My problems are below the code because I need you to read the code in order to be clear.

This is my file from where i will export the route(registration.js):

const express = require("express");
const router = express.Router();
console.log("azerty");
router.post("/register", (req, res)=>{
    console.log("qwerty");
    res.stautus(200).send("hello");
});
module.exports = router;

This is my main file to where i will export the route (app.js):

const express = require("express");
const app = express();
...
app.use("/register", require("./registration.js"));

This is my html form:

<form action="/register" method="post">
            <input type="text" placeholder="First Name" name="fstName" required/>
            <input type="text" placeholder="Last Name" name="lstName"required/>
            <input type="submit" value="Submit"/>
</form>

I have some other issues related to this:

  • first: why does azerty log to the console when I'm at http://localhost:3000/ ?
  • second: why I keep getting Cannot POST /register and in the developer tool a 404 error? And my code inside the route handler doesn't run.
  • lastly: Is this the right way to export routes(like using the express.Route() in the routing file and express() only in the main one)?

first: why does azerty log to the console when I'm at http://localhost:3000/ ?

console.log("azerty") is in file scope of registration.js , so will be logged as soon as your app.js requires it.

This line here is enough to triger the console logging: app.use('/register', require('./registration')); becuase module is required when express mounts it as middleware on start

second: why I keep getting Cannot POST /register and in the developer tool a 404 error? And my code inside the route handler doesn't run.

Becuase it is not mounted where you think it is mounted.

router.post("/register ... Here you've mounted at /register path, and then app.use("/register", require("./registration.js")); here you've mounted to another /register path. Combine the two together, you get full path as /register/register (Also check the typo mentioned in comment)

So to mount at localhost:3000/register , you've to define like (Note the differences):

router.post("/", (req, res)=>{ ...

// and then
app.use("/register", require("./registration.js"));

// or simply
router.post("/register", (req, res)=>{ ...

// and then
app.use(require("./registration.js"));

lastly: Is this the right way to export routes(like using the express.Route() in the routing file and express() only in the main one)?

Yes, it's perfectly fine. But keep in mind the mount path.

azerty was logged to the console that means the route was imported and it worked.

You have already exported the route in the right way. I think you shoud use return before res.stautus(200).send("hello"); in registation.js . Like that:

const express = require("express");
const router = express.Router();
console.log("azerty");
router.post("/", (req, res)=>{
    console.log("qwerty");
    return res.stautus(200).send("hello");
});
module.exports = router;

To use this request, the api looks like: localhost:3000/register

I think you added a prefix to the route with app.use("/register"...) and now it is /register/register

Juste remove it in app.js or in your route file

const express = require("express");
const router = express.Router();
console.log("azerty");
router.post("/register", (req, res)=>{
    console.log("qwerty");
    res.stautus(200).send("hello");
});
module.exports = router;
const express = require("express");
const app = express();
...

app.use(require("./registration.js"));

I don't know if it is the right way here's what i do its kinda like you

//src/app.js
// Import
import postRoutes from './routes/post';
import authRoutes from './routes/auth';

...
// Endpoints

app.use(postRoutes);
app.use(authRoutes);
// src/routes/post.js

...

const Router = express.Router();

/**
 * Routes
 */

Router.get('/post', getPosts);
Router.post('/post', isAuth,  creationValidation(), createPost);
Router.put('/post/:id', isAuth, editValidation(), putPost);
Router.delete('/post/:id', isAuth, deletePost);



/**
 * Export
 */
export default Router;

Firstly, azerty is getting logged because it's not nested inside any functions. It will simply log on runtime and you being at http://localhost:3000/ has no influence on this.

Second, you Cannot POST /register because when using router, the root is the first parameter passed to app.use - in your current setup, /register/register is the route. To fix this, change the first parameter of router.post in registration.js to just / :

const express = require("express");
const router = express.Router();
console.log("azerty");
router.post("/", (req, res)=>{
    console.log("qwerty");
    res.status(200).send("hello");
});
module.exports = router;

Finally, for exporting routes this is the most common setup I see.

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