I'm trying to export a router 'Accounts' to use in my app. The 'Accounts' router has the paths '/login' (POST), '/register'(POST), 'login' (GET), and '/logout' (POST). In my index app I am using the router with the path '/account'. So the paths should be:
/account/login (POST)
/account/login (GET)
/account/register(POST)
/account/logout (GET)
But when I call these paths they aren't found by the app:
How do I get the paths in the 'accounts.js' router to work in the 'index.js' app?
My file structure is like this:
my account.js file looks like this:
const express = require('express');
const passport = require('passport');
const Account = require('../models/Account');
const Branch = require('../models/Branch')
const router = express.Router({mergeParams: true});
const registerAccount = (req, res, next) => {
//register the account
};
const createUser = (req,res) => {
//create a user in another db
}
router.post('/register',
[registerAccount, createUser]);
router.get('/login', function(req, res) {
res.json(user);
});
router.post('/login', passport.authenticate('local', { successRedirect: '/',
failureRedirect: 'account/login' }));
router.get('/logout', function(req, res) {
req.logout();
res.redirect('/');
});
});
module.exports=router;
and my index.js looks like this:
// index.js
var express = require("express");
var bodyParser = require("body-parser");
var jwt = require("jwt-simple");
var auth = require("../auth/auth.js")();
var users = require("./users.js");
var cfg = require("../config.js");
const accountController = require('./account');
var app = express();
app.use(bodyParser.json());
app.use(auth.initialize());
app.use('/account',accountController);
app.get("/", function(req, res) {
res.json({
status: "My API is alive!"
});
});
app.post("/token", function(req, res) {
//some token stuff that doesn't matter here
});
module.exports = app;
For starters, you don't pass an array to a router.post(), so change this:
router.post('/register', [registerAccount, createUser]);
to this:
router.post('/register', registerAccount, createUser);
And make sure that registerAccount calls next() when it's done and wants createUser() to get called.
In the doc, for this syntax:
app.post(path, callback [, callback ...])
the brackets in [, callback] mean that parameter is optional. The brackets are not supposed to be used.
Related
whats wrong with my code? its showing no results....although it kinda works when i use google.com as url but in other cases it shows no results*I haven't shared my api key here(appid=)
const express = require('express');
const app = express();
const http = require('http');
app.get("/", function(req, res) {
const url= 'https://api.openweathermap.org/data/2.5/weather?q=london&appid='
http.get(url, function(response){
console.log(response);
// response.on("data", function(data){
// const weatherData = JSON.parse(data);
// const temp = weatherData.main.temp;
// // const weatherDescription = weatherData.weather[0].description;
// res.send(temp)
// })
// res.send('server is sending');
})
})
app.listen(3000, function(req, res){
console.log('Server is alive')
})
Can anyone help me figure out why my express routes arent working please. I have been stuck for days trying to figure this out but I keep getting 404 errors when I got to any of the routes in customer.js
<--------------------main server-------------->
var express = require("express");
var path = require('path');
var app = express();
var indexRouter = require('./routes/index');
var ordersRouter = require('./routes/orders');
var customersRouter = require('./routes/customers');
var productsRouter = require('./routes/products');
app.use('/', indexRouter);
app.use('/customers', customersRouter);
app.use('/orders', ordersRouter);
app.use('/products', productsRouter);
app.listen(80);
module.exports = app;
one of my route files below the only route file works is the index router.
var express = require('express');
var router = express.Router();
router.get('/customers', function(req, res, next) {
console.log(req.status())
res.send('<p>some html</p>');
});
router.post('/customers/update/shipping', function(req, res) {
res.send('<p>someg html</p>');
});
router.post('/customers/update/billing', function(req, res) {
res.send('<p>somew html</p>');
});
router.post('/customers/update/cart', function(req, res) {
res.send('<p>some dhtml</p>');
});
module.exports = router;
<------------------------------------------------------>
In your customers files your routes will already be relative to /customers. remove the leading /customers from all your routes. For e.g:
router.get('/customers', function(req, res, next) {
console.log(req.status())
res.send('<p>some html</p>');
});
Should just be
router.get('/', function(req, res, next) {
console.log(req.status())
res.send('<p>some html</p>');
});
same principle applies for the other files.
I'm making an app the will let different users see the different root page. Let's say there are two groups: admin and viewer. What I want to do is like:
var admin = require('./routes/admin');
var viewer = require('./routes/viewer');
app.get('/', function(req,res,...) {
if (req is admin) app.use('/', admin);
else app.use('/', viewer);
});
Is this possible, or I should redirect them to different paths? Thanks!
This needs to be done by redirecting a route to other route according to the requirement.
This can be done using below code:
var express = require('express');
var app = new express();
app.get('/', function(req, res, next) {
if(true) { //group check
res.redirect('admin');
} else {
res.redirect('viewer')
}
});
app.use('/admin', function(req, res, next) {
res.send('admin')
});
app.use('/viewer', function(req, res, next) {
res.send('viewer')
});
app.listen(3000);
So i have been racking my brain for quite awhile now trying to figure this out and I'm still having issues.
So i define a route like this:
var home = require('./routes/home');
var app = express();
app.use('/home/:client', home);
And my home.js code looks like this:
var express = require('express');
var router = express.Router();
router.get('/', function(req, res, next) {
res.render('homeview', { title: 'Welcome',
user: username});
});
router.get('/:client', function(req, res, next) {
var theClient = req.params.client;
console.log(theClient)
});
module.exports = router;
And then when i try to go to this URL:
http://www.localhost:3000/home/client
Nothing happens. For some reason it never gets to the second router.get and never logs anything. Anyone notice whats wrong?
Working solution # https://github.com/rmjoia/expressRoutes
app.js
var express = require('express'),
app = express(),
port = process.env.PORT || 3000,
homeRouter = require('./home');
app.use('/home', homeRouter);
app.route('/')
.all(function (request, response, next) {
// Do some plumbing stuff
next();
})
.get(function (request, response, next) {
response.send('OK GET - Hello Stack Overflow');
next();
});
app.listen(port, function (error) {
if (error) {
console.error(error.message);
}
else {
console.info('Server up and running. Listening on port ' + port);
}
})
home.js
var express = require('express');
var homeRouter = express.Router();
var router = (function (router) {
// define the home page route
router.get('/', function (req, res) {
res.send('home route - homepage');
});
// define the about route
router.get('/:client', function (req, res) {
res.send(req.params.client);
});
return homeRouter;
})(homeRouter);
module.exports = router;
All:
When I learn how to upload file with Express.js, there is a middleware called multer ( https://github.com/expressjs/multer ), and from its Usage example:
var express = require('express')
var multer = require('multer')
var upload = multer({ dest: 'uploads/' })
var app = express()
app.post('/profile', upload.single('avatar'), function (req, res, next) {
// req.file is the `avatar` file
// req.body will hold the text fields, if there were any
})
app.post('/photos/upload', upload.array('photos', 12), function (req, res, next) {
// req.files is array of `photos` files
// req.body will contain the text fields, if there were any
})
var cpUpload = upload.fields([{ name: 'avatar', maxCount: 1 }, { name: 'gallery', maxCount: 8 }])
app.post('/cool-profile', cpUpload, function (req, res, next) {
// req.files is an object (String -> Array) where fieldname is the key, and the value is array of files
//
// e.g.
// req.files['avatar'][0] -> File
// req.files['gallery'] -> Array
//
// req.body will contain the text fields, if there were any
})
The middleware object directly used in app.js, I wonder if I use sub router like:
app.js
var routes = require('./routes/index');
app.use("/", routes);
index.js
var express = require('express');
var router = express.Router();
/* GET home page. */
router.get('/', function(req, res, next) {
res.render('index', { title: 'Express' });
});
router.post('/upload', function(req, res, next) {
debugger;
console.log(req.body.upld);
console.log(req.file);
res.send("");
});
module.exports = router;
I wonder where should I put that upload middleware? Should I put that var upload = multer({ dest: 'uploads/' }) in each file use it? If so, will this cause several uploads folders generated in different folders based on the router file located?
Thanks