I am trying to build my express app to have routes within routes as shown below and I am getting a 404 error.
What I am trying to do is simply, route all traffic with api in the route to the routes/api.js file, then from there, based on the end of the url, depending on if its signup or login, route to the corresponding signup.js or login.js file.
Note, moving the code from routes/signup.js to routes/app.js works perfectly fine.
Has anyone gotten unexpected 404 errors under a similar set up? I appreciate any suggestions on how to resolve.
server/index.js
import express from 'express';
const app = express();
app.use('/api', require('./routes/api'));
app.use('*', (req,res) => {
res.status(404).send('404: Not Found');
});
app.listen(3000, function() {
console.log('api is running on port 3000');
});
server/routes/api.js
var express = require("express");
var router = express.Router();
router.use('/signup', require('./signup'));
router.use('/login', require('./login'));
module.exports = router;
server/routes/signup.js
var express = require("express");
var router = express.Router();
router.post('/api/signup', (req, res) => {
res.send('HELLO WORLD');
});
module.exports = router;
Related
When I open the site page it shows Cannot GET /
I tried reading other posts about this problem, but I can't seem to fix this. I am new to this and can not figure this out myself.
require('./config/db');
const app = require('express')();
const port = 3000;
const UserRouter = require('./api/User');
const bodyParser = require('express').json;
app.use(bodyParser());
app.use('/user', UserRouter)
app.listen(port, () => {
console.log(`Server running on port ${port}`);
})
Every route inside UserRouter start with /user
If you did something like this :
var express = require('express');
var router = express.Router();
router.get('/signup', function(req, res) {
/* http://localhost:${port}/user/signup */
});
//Put at the end or will be trigered every time you call a route starting with /user
router.get('*', function(req, res) {
/* http://localhost:${port}/user */
});
signup will be able to access logging inside /User route
I am trying to use routers in my Node js application. I cannot execute router.get functiom
In the main file which is server.js I used this script
// Routes
app.use('/api/v1/stores', require('./routes/stores'));
But in the route file which is stores.js, I cannot enter the router.get function and execute it
const express = require('express');
const router = express.Router();
console.log("I can reach this point")
router.get('/', (req, res) => {
console.log("I can not reach this point")
res.send('app/about');
});
module.exports = router;
That's because new express version 4.17.* is different when handling routes. try,
const express = require('express');
const app = express();
app.get('/', (req, res) => {
res.send('app/about');
});
module.exports = app;
For more details: https://expressjs.com/en/guide/routing.html
you can try this way also, in your store.js file create something like this.
module.exports = app => {
app.get('/', (req, res) => {
res.send('app/about');
});
}
and add this require to server.js
require('./store')(app);
i'm trying to use postman with "post" method , but when i use it i'm getting a 404 not found error.
i will attach my code and a picture of the error
thanks in advance
using React Native
const express = require('express');
const router = express.Router();
router.post('/signup', (req, res) => {
res.send('You made a post request');
});
module.exports = router;
Picture from Postman app with the error
Things to consider are
1. Make sure you have imported the routes in app.js and used them.
2. Your app is running on 3000 port.
const UserRouter = require('./routes/v1');
app.use('/api',UserRouter);
const port = process.env.PORT || 3000;
app.listen(port, function() {
console.log("listening at port",port)
});
I'm new to node and express, was trying to test some basics routes but getting a Type Error: Router.use() requires a middle ware function but got an object
This is what I have in app.js
const express = require('express');
const routes = require('./routes/api');
// set up express app
const app = express();
app.use('/api', routes);
//listen for request
app.listen(process.env.port || 4000, function(){
console.log('now listening for requests');
});
and in my api.js:
const express = require('express');
//store router object to a vairable to enable us use routes on api.js
const router = express.Router();
router.get('/ninja', function(req, res){
res.send('{type: "GET"}');
})
router.post('/ninja', function(req, res){
res.send({type: "POST"});
})
//to update an api, where id is a parameter.
router.put('/ninja/:id', function(req, res){
res.send({type: "PUT"});
})
//to delete an api
router.get('/ninja/:id', function(req, res){
res.send({type: "DELETE"});
})
module.exports = router;
I have tried exporting router on each file, none worked.
I m still trying to learn NodeJs but I came across this path thing I encountered in Express. When I create an app using Express I noticed that in app.js I have these lines of code var index = require('./routes/index');
var users = require('./routes/users');
app.use('/', index);
app.use('/users', users);
And in users.js I already have configured
var express = require('express');
var router = express.Router();
/* GET users listing. */
router.get('/', function(req, res, next) {
res.send('respond with a resource');
});
module.exports = router;
I don t really understand why is it in users.js router.get('/') instead of router.get('/users') as it is specified in app.js? Can someone explain a bit what s going on in this case?
As far as I understand in app.js it says whenever someone tries to access the specified route('/users') lets say localhost:3000/users in the browser, let the file required in users variable handle it.
If you are working with routes the express app is automatically . Here is an example from the express.js website:
In our router file we have:
var express = require('express')
var router = express.Router()
// middleware that is specific to this router
router.use(function timeLog (req, res, next) {
console.log('Time: ', Date.now())
next()
})
// define the home page route
router.get('/', function (req, res) {
res.send('Birds home page')
})
// define the about route
router.get('/about', function (req, res) {
res.send('About birds')
})
module.exports = router
Then in our main file were we have our server etc we load in the router:
var birds = require('./birds')
// ...
app.use('/birds', birds)
These routes in the router app are only accessed when there is a request to to /birds url. All the routes in the router are now automatically staring with /birds
So this code in the express router:
// im code in the birds router
router.get('/about', function (req, res) {
res.send('About birds')
})
Is only executed when someone makes a get request to the /birds/about url.
More information in the official express.js docs
I would just like to point out what I have learnt today after some frustration, and maybe somebody can elaborate as to why this happens. Anyway, if, like me, you want to use '/users' for all user routes or '/admin' for all administrator routes then, as WillemvanderVeen mentioned above, you need to add the following code to your main app.js file
var users = require('./routes/users')
app.use('/users', users)
However, one thing which was not mentioned is that the order with which you declare your 'app.use('/users', users)' in app.js is important. For example, you would have two route handling files as so:
/routes/index.js
const express = require('express');
const router = express.Router();
router.get('/', (req, res) => { res.render('index') });
/routes/users.js
const express = require('express'); const router = express.Router();
router.get('/', (req, res) => { res.send('users route') })
You would then require them in your main app.js file as so:
app.js
const express = require('express');
const app = express();
const index = require('./routes/index');
const users = require('./routes/users');
app.use('/', index);
app.use('/users', users);
and you would expect that when you hit the '/users' route that you would receive the res.send('users route') page.
This did not work for me, and I struggled to find any solution until recently, which is why I am now commenting to help you.
Instead, I swapped the app.use() declarations in app.js around like so and it worked:
app.js
const express = require('express');
const app = express();
const index = require('./routes/index');
const users = require('./routes/users');
app.use('/users', users);
app.use('/', index);
Now when I hit '/users' I see the 'users route' message. Hope this helped.
To answer your question though, when you configure the route handler in app.js as users, then you are requiring a router file (./routes/users) to handle all requests from that file and sending them to the URL /users first. So if you do the following:
/routes/users.js
router.get('/dashboard', (req, res) => {
// get user data based on id and render it
res.render('dashboard')
});
then whenever user is logged in and goes to dashboard, the URL will be /users/dashboard.