Express route with dynamic params not working - javascript

router.get('/:id ', (req, res) => {
res.send(req.params.id);
});
When I call this on exmaple "http://localhost/12" I will get an error called "Cannot Get /12"
Any ideas what I am missing out?

You need to register your router to main app in your index.js
In your router.js folder
const express = require('express');
const router = express.Router()
router.get('/:id ', (req, res) => {
res.send(req.params.id);
});
and in your index.js
const express = require('express');
app = express()
app.use(router)

Related

Parameter express can't be passed with require

app.js
const express = require("express");
const app = express();
app.use("/", require("./routers.js")(app));
app.listen(3000);
router.js
module.exports = function (app) {
console.log(app);
app.get("/", (req, res) => {
res.json(5);
});
};
The error given by the Console is: " TypeError: Router.use() requires a middleware function but got an undefined "
I don't understand why I can't pass the express app(app.js) through routers( in this way I don't redeclare the express and app variable in router.js ).
Don't pass app to routes better to create a new router and pass to the app.
router.js
const express = require("express");
const router = express.Router();
router.get("/", (req, res) => {
res.json(5);
});
module.exports = router;
app.js
app.use("/", require("./routers.js"));
As you mention in the comment, you don't have to add an inside app.use
module.exports = function (app) {
app.get("/", (req, res) => {
res.json(5);
});
};
// app.js
require("./routers.js")(app);
The use method of Express needs a callback of three parameters, not the app itself, so you need something like this:
In routes.js
exports.doSomeThing = function(req, res, next){
console.log("Called endpoint");
res.send("Called endpoint");
}
In your index.js
const Express = require("express");
const app = Express();
const routes = require("./routes");
app.use("/", routes.doSomeThing);
app.listen(3030, () => {
console.log("Listening on port 3030");
});
This approach doesn't need to include the express router but this may not be adecuate for big scale projects I recommend you to read express router documentation:
https://expressjs.com/es/guide/routing.html#express-router

How am I supposed to use app.METHOD in Node.js?

so I'm trying to make a simple "route system", that would handle requests and send them to a certain controller.
The problem is that I can't even handle any route, because I get
Cannot GET /
error in response.
app.js
const express = require('express')
const router = require('./routes/routes')
const app = express()
const port = 3000
app.engine('.html', require('ejs').__express)
app.set('view engine', 'html')
router.load()
app.listen(port, () => {
console.log(`Waiting on :${port}`)
})
routes.js
const express = require('express')
const app = express()
// Route config
const routes = {
['/']: {
controller: 'index',
method: 'get'
},
}
// Load routes
const load = () => {
for (const route in routes) {
app[routes[route].method](route, (req, res) => {
// Do something
})
}
}
exports.load = load
You don't use your router file in app.js, try that:
app.js
const express = require('express')
const router = require('./routes/routes')
const app = express()
const port = 3000
app.engine('.html', require('ejs').__express)
app.set('view engine', 'html')
app.use('/', router);
router.load()
app.listen(port, () => {
console.log(`Waiting on :${port}`)
})
routes.js
var express = require('express');
var router = express.Router();
router.get('/', function(req, res, next) { res.send({ success: true }); });
module.exports = router;
It's useless and unreadeable create an array whit your all your routes.
My suggestion is to try use command by terminal express my_app for generate the base structure and try to use it or at least read for see how it's work.
You seem to be lacking the context for how the routing system works within Express.
As a starting point, please create a project with the below structure, and try creating your own route to ensure you have a grasp on how to utilize them properly.
Create a new project folder
cd into the project folder from within your terminal
run npm init -y
Run npm i express dotenv
Create a file named app.js in the root of your project folder and place the below code inside of it:
require('dotenv').config();
const express = require('express');
const app = express();
app.use(express.json({limit: '30mb', extended: true}));
app.use(express.urlencoded({ extended: true }));
app.listen(process.env.PORT || 3000, () => {console.log('Server successfully started')});
app.get('/', (req, res) => {
return res.send('Hello, World!');
});
Create a new folder named routes
Create a new file named test.js and place it inside of the routes folder
Place the below code in the test.js file.
const router = require('express').Router();
router.get('/', (req, res) => {
return res.send('Hello from your custom route!');
});
module.exports = router;
Go back into your app.js file and add the below lines of code to the bottom of the file
const testRoute = require('./routes/test');
app.use('/test', testRoute);
In your terminal, run node app.js
Make a GET request to http://localhost:3000/test by navigating to it with your browser, or by using a REST client, such as Postman.
Once you have completed these steps, you should understand the basic concept of Express routing.
You can use the router combined with Express Middleware to re-route your user to the proper controller based on the endpoint they are trying to access / the data they are trying to send.
Please test with this code
const express = require('express')
const app = express();
app.get('/', (req, res) => {
res.json({"message": "Welcome! it's working"});
});
The complete code is here on Github

Why I get TypeError('Router.use()

I have index.js file like this and
const express = require('express');
const app = express();
//Import Routes
const authRoute = require('./routes/auth');
//Route Middlewares
app.use('/api/user', authRoute);
app.listen(3000, () => console.log('Server Up and running'));
auth.js like this one
const router = require('express').Router();
router.post('/register', (req, res) => {
res.send('Register');
})
module.exports = router;
Why i get the TypeError('Router.use() requires a middleware function but got a ' + gettype(fn))
^
TypeError: Router.use() requires a middleware function but got a Object
at Function.use (C:\Users\xxx\Desktop\Websites\Authentication\node_modules\express\lib\router\index.js:458:13)
at Function. (C:\Users\xxx\Desktop\Websites\Authentication\node_modules\express\lib\application.js:220:21)
You may try to re-write your auth.js in the following format, I think that will solve the issue:
router.route('/register').post((req, res) => { .............

Api : Express : throw new TypeError('Router.use() requires a middleware function but got a ' + gettype(fn))

I have just started with api building using express but getting below error.
below is my code. please help.
Server.js code
const express = require('express');
const mongoose = require('mongoose')
const users = require('./routes/api/users');
const profile = require('./routes/api/profile');
const posts = require('./routes/api/posts');
const app = express();
//DB config
const db = require('./config/keys').mongoURI;
//connet to MongoDB
mongoose
.connect(db)
.then(() => console.log('MongoDB connected'))
.catch(err => console.log(err));
app.get('/', (req, res) => res.send('Hello Ajas Bakran'));
//Use Routes
app.use('/api/users', users);
app.use('/api/profile', profile);
app.use('/api/posts', posts);
const port = process.env.PORT || 5000;
app.listen(port, () => console.log(`Server running on port ${port}`));
users.js code
const express = require('express');
const router = express.Router();
router.get('/test', (req, res) => res.json({msg:'Hello Users'}));
module.exports = router;
profile.js code
const express = require('express');
const router = express.Router();
router.get('/test', (req, res) => res.json({msg:'Hello profile'}));
module.exports = router;
posts.js
const express = require('express');
const router = express.Router();
router.get('/test', (req, res) => res.json({msg:'Hello posts'}));
module.exports = router;
I refered few answers on stackoverflow, but moslty solution to that was having module.exports = router; this line at the end. but i do have the line present already still i get the same error. Really not sure what is going wrong
From what I can see I think you need to re-write this portion:
router.route('/')
instead of
router.get
Usually these types of error originate from non properly exported router.

Node.js Express export routes for organization?

Utilizing express.Router() for API calls to/from our application:
var express = require('express');
var app = express();
var router = express.Router();
router.use console.logs before every API call:
router.use(function(req, res, next) { // run for any & all requests
console.log("Connection to the API.."); // set up logging for every API call
next(); // ..to the next routes from here..
});
How do we export our routes to folder/routes.js and access them from our main app.js, where they are currently located:
router.route('/This') // on routes for /This
// post a new This (accessed by POST # http://localhost:8888/api/v1/This)
.post(function(req, res) {
// do stuff
});
router.route('/That') // on routes for /That
// post a new That (accessed by POST # http://localhost:8888/api/v1/That)
.post(function(req, res) {
// do stuff
});
...when we prefix every route with:
app.use('/api/v1', router); // all of the API routes are prefixed with '/api' version '/v1'
In your new routes module (eg in api/myroutes.js), export the module.
var express = require('express');
var router = express.Router();
router.use(function(req, res, next) {
console.log('Connection to the API..');
next();
});
router.route('/example')
.get(function(req, res) { });
.post(function(req, res) { });
module.exports = router;
Then you can require the module in your main server/app file:
var express = require('express');
var app = express();
var myRoutes = require('./api/myRoutes');
app.use('/api', myRoutes); //register the routes
In your app.js file you can have the following:
//api
app.use('/', require('./api'));
In the folder api you can have 'index.js` file, where you can write something like this:
var express = require('express');
var router = express.Router();
//API version 1
router.use('/api/v1', require('./v1'));
module.exports = router;
In the folder v1 file index.js something like this:
var express = require('express');
var router = express.Router();
router.use('/route1', require('./route1'));
router.use('/route2', require('./route2'));
module.exports = router;
File route1.js can have the following structure:
var express = require('express');
var router = express.Router();
router.route('/')
.get(getRouteHandler)
.post(postRouteHandler);
function getRouteHandler(req, res) {
//handle GET route here
}
function postRouteHandler(req, res) {
//handle POST route here
}
module.exports = router;
route2.js file can have the same structure.
I think this is very comfortable for developing the node project.

Categories

Resources