I have read through posts about this issue but I just can't figure out what I am doing wrong.
What I would like is to separate each of my route (login and register for now) into their own separate file, reference those files in routes/user/index, then use that in server.js. This is what I have now:
server.js
ROUTES
USER
index.js
LOGIN
index.js
REGISTER
index.js
server.js
const express = require("express");
const app = express();
(...)
app.use("/user", require("./routes/user"));
(...)
routes/user/index.js
const express = require("express");
const router = express.Router();
router.use("/login", require("./login"));
router.use("/register", require("./register"));
module.exports = router;
routes/user/login/index.js
const express = require("express");
const router = express.Router();
router.post("/login", async (request, response) => {
(...)
});
module.exports = router;
routes/user/register/index.js
const express = require("express");
const router = express.Router();
router.post("/register", async (request, response) => {
(...)
});
module.exports = router;
All I get is a 404 error. Any help would be appreciated.
Thanks!
You can create chainable route handlers for a route path by using app.route()
const express = require("express");
const router = express.Router();
router.route("/login").post((request, response) => {
//Your code goes here
});
module.exports = router;
OK, after a few more hours of googling & trial/error I finally figured it out. For some reason I didn't find earlier this setup guide but it was pretty much what I wanted.
Related
Started working on a new application and decided to write tests from very early stage to avoid any future mistakes. However, little bit struggling I guess with setting up the Jest correctly. I made a follow on few tutorials and documentation, but the result is not the one I'm expecting. What I am trying to do is to make a basic test for creating a user, however I receive and error:
error: Error: cannot POST /register (404)
I get the point that the test can't find the endpoint /register, but I thought that is the point to keep server.js and app.js for supertest, because he will be smart enough to understand the path to this endpoint, which actually is: "/api/v1/auth/register". I want to mark that the registration process works fine trough postman.
Here is the app.js:
require("dotenv").config();
require("express-async-errors");
const express = require("express");
const app = express();
// routers
const authRouter = require("./src/routes/auth/auth.router");
// packages
const morgan = require("morgan");
const fs = require("fs");
const cookieParser = require("cookie-parser");
// middlewares
const errorMiddleware = require("./src/middlewares/errorMiddleware");
app.use(express.json());
app.use(cookieParser(process.env.ACCESS_TOKEN));
app.use(morgan("common", {
stream: fs.createWriteStream("./src/utils/logs/logs.log", {
flags: "a"
})
}));
// endpoints
app.use("/api/v1/auth", authRouter);
app.use(errorMiddleware);
module.exports = app;
Here is the server.js:
const app = require("./app");
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}...`);
});
Here is the auth.test.js:
const request = require("supertest");
const app = require("../../../app");
describe("POST /register", () => {
it("Should create a new user", async () => {
const response = await request(app).post("/register").send({
email: "superemail#gmail.com",
username: "superusername",
password: "superpassword"
});
console.log(response); // I see here the 404 error.
});
});
Not sure if it helps, but here is the router file:
const express = require("express");
const router = express.Router();
const {check} = require("express-validator");
const {registerUserController, loginUserController} = require("../../controllers/auth/auth.controller");
router.post("/register", [
check("email").trim().not().isEmpty().isEmail(),
check("username").trim().not().isEmpty().isString(),
check("password").trim().not().isEmpty().isString().isLength({
min: 6
}).withMessage("Password has to be at least 6 characters long"),
check("firstName").optional().trim().not().isEmpty().isString(),
check("lastName").optional().trim().not().isEmpty().isString(),
check("age").optional().trim().not().isEmpty().isNumeric().isInt({
min: 0
}).withMessage("Age can't be less than 0"),
], registerUserController);
module.exports = router;
Hey guys so I have the following in my app.js file
const express = require("express");
const app = express();
const path = require('path');
const hbs = require("express-handlebars");
app.engine(
"hbs",
hbs({
extname: "hbs",
//defaultLayout: "layout",
layoutsDir: __dirname + "/views/layouts/"
})
);
app.set("views", path.join(__dirname, "views"));
app.set("view engine", "hbs");
I also have a file located in server/views/layouts/ that is a handle bars file called share.hbs
I also have a file in my server/api/media.js that looks like this
const express = require("express");
const router = express.Router();
const database = require("../db");
router.get("/share", async (req, res, next) => {
res.render("share");
});
But when ever I try to render the file it errors out with the following error
Had to move my file out of the layouts folder and add this to the res.render call
res.render("share.hbs", { layout: "share" });
Banging my head on this. in Express app, my get request works fine. However attempting to POST results passes an empty req.body.
here is my file tree:
index.js:
const express = require('express');
const apiRoute = require('./routes/api/index.js');
const bodyParser = require('body-parser');
// const morgan = require('morgan');
const app = express();
app.use(function(req, res, next) {
if (req.headers['content-type'] === 'application/json;') {
req.headers['content-type'] = 'application/json';
}
next();
});
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: true
}));
app.use('/api', apiRoute);
app.listen(3000);
routes/api/index.js
const express = require('express');
const router = express.Router();
const entityRoute = require('./entity');
router.use('/entity', entityRoute);
module.exports = router;
routes/api/entity.js:
const express = require('express');
const router = express.Router();
const db = require('../../database');
router.get('/', function(req, res) {
db.select().from('entity').then(function(data) {
res.send(data);
});
});
router.post('/', function(req, res) {
console.log(req.body);
res.send(req.body);
});
module.exports = router;
Adding my Postman request in response to comment:
I have been over this numerous times, checked body-parser docs and other SO answers and can't figure this out.
following the comments, submitting json body works. screenshot below:
Not sure why this doesnt work the other way...
Can someone help me why default route is not working in my Mean App, But the next routing works
Here when I open http://localhost:3000 I am not able to see any output, But I have defined route in route.js which is working
var express = require('express');
var cors = require('cors');
var bodyparser = require('body-parser');
var mongoose = require('mongoose');
var path = require('path');
const port = 3000;
app.get('/', function (req, res) {
res.send('Test');
console.log('Opened the root path');
});
When I open the page with http://localhost:3000/main I am able to see the Output and also log written in the console
const express = require('express');
const router = express.Router();
router.get('/main', function (req, res, next) {
res.send('This is the Admin Landing Page');
});
router.get('/install', function (req, res, next) {
res.send('This is the Install Landing Page');
console.log('Opened the Install path');
});
module.exports = router;
It looks like you the code you pasted is the full version, and it's not runnable because:
You did not declare app variable.
You did not start the http server.
It's really hard to tell the root cause what's wrong of your code. Following codes works for me:
const express = require('express');
const port = 3000;
let app = express();
app.get('/', function (req, res) {
res.send('Test');
console.log('Opened the root path');
});
let server = require('http').createServer(app);
server.listen(port, function() {
console.log('Server started');
});
I am learning express js 4.0 and building compact CRUD REST API web application with it. In the tutorial, it shows two ways; using app and using router.
//using router
var router = express.Router();
router.get('/', function(req,res){
res.send('hello, world')
});
//using app
app.get('/', function(req,res){
res.send('hello, world')
});
To me, I feel they work same but I don't know why people use router, I think using app is more simple. Can anybody explain what is difference between them?
It allows for modularity. A lot of people have a routes folder that they keep all their route handlers in. And then in their app.js file, they just do something like app.use(<prefix>, <routes>); after they require their router. It keeps your files smaller and more organized.
Example:
app.js
var express = require('express');
var rootRoutes = require('./routes/index');
var userRoutes = require('./routes/user');
var app = express();
app.use('/', rootRoutes);
app.use('/user', userRoutes);
module.exports = app;
routes/index.js
var express = require('express');
var router = express.Router();
router.get('/', function(req, res) {
res.render('index.jade');
});
router.get('/about', function(req, res) {
res.render('about.jade');
});
module.exports = router;
routes/user.js
var express = require('express');
var router = express.Router();
router.get('/:name', function(req, res) {
var userName = req.params.name;
res.render('user.jade', {
userName: userName
});
});
module.exports = router;