Here my server code
var express = require("express");
var isAuthen = require('./middleware/authorize')
var router = express.Router();
var app = express();
var order_process = require('./routes/order-process');
app.use('/order',isAuthen, order_process);
and here order_process code
var express = require('express');
var bodyParser = require('body-parser');
const bcrypt = require("bcrypt");
var router = express.Router();
var db = require('../models/database');
router.get('/', urlencodedParser, function (req, res) {
try {
console.log(req.params);
}catch(err){
console.log(err);
}
module.exports = router;
http://localhost:3000/order/2
as i know that url should return number 2 ??
i dont know why it cannot return ?
should return correct params from url
Here's an example of how to get the params from a route:
const express = require('express');
const router = express.Router();
const app = express();
app.use('/order', router);
router.get('/:page', (req, res) => {
res.send(`You are viewing page ${req.params.page}`);
});
const server = app.listen(8000);
Then go to http://localhost:8000/order/2 and you should see it say:
You are viewing page 2
Related
I am having this issue
route.setRouter(app)
TypeError: route.setRouter is not a function
in the cmd
this is my app.js
const express = require('express');
const bodyParser = require('body-parser');
const fs = require('fs');
const app = express();
const mongoose = require('mongoose');
const appConfig = require('./config/appConfig');
const socketLib = require('./app/libs/socketLib');
mongoose.set('useCreateIndex', true);
app.use(bodyParser.json());
// require routes
const routesPath = './app/routes'
fs.readdirSync(routesPath).forEach(file => {
if (~file.indexOf('.js')) {
let route = require(routesPath + '/' + file);
route.setRouter(app);
}
});
and i have already installed express
I think you want to set up the routes the other way round, i.e. through app.use(router)
For example if your router-module contains the following:
/* router-test.js */
const express = require('express')
const router = express.Router()
router.get('/test', function (req, res) {
res.send('Test from router')
})
module.exports = router;
Then, you can set up the router as follows:
const testRouter = require('./router-test');
...
app.use(testRouter);
// alternatively you can plug your router in beneath a path:
app.use('/somePath', testRouter);
So in your case you should probably do (note that I've changed the bitwise ~ and .indexOf() by the much simpler .includes()):
fs.readdirSync(routesPath).forEach(file => {
if (file.includes('.js')) {
let route = require(routesPath + '/' + file);
app.use(route);
}
});
I'm doing to some refactoring in my application and I don't understand why this case is failing.
index.js
const express = require('express');
const router = express.Router();
const models = require('../models');
const listRoute = require('./list');
router.use('/list', listRoute);
list.js
const express = require('express');
const router = express.Router();
const models = require('../models');
const sendListDataToView = (req, res, view) => {
// get data from backend and pass to template
}
router.route('/list/show/:id')
.get((req, res) => {
sendListDataToView(req, res, 'view-list')
})
router.route('/list/expand-records-forms/:id')
.get((req, res) => {
sendListDataToView(req, res, 'edit-list-records')
})
module.exports = router;
Trying to navigate to /list/show/3 throws a 404 error. However, if I move the definitions of these routes and sendListDataToView to index.js, the page loads fine. Is this because of the multiple router.routes?
I'm just going to wipe my original answer.
You need to create the app.
const express = require('express');
const app = express();
const models = require('../models');
const listRoute = require('./list');
app.use('/list', listRoute); // Using express now.
app.listen(8080); // starts server
Im trying to link a route to a controller vs doing the code within the route definiton. Here is my controller:
const {mongoose} = require('../db/mongoose');
const {Order} = require('../models/order');
module.exports.listAllJson = function(req, res) {
res.send({"Here": "something"});
}
And here is my server.js file:
var express = require('express');
var bodyParser = require('body-parser');
var fs = require('fs');
var schedule = require('node-schedule');
var {mongoose} = require('./db/mongoose');
var {Order} = require('./models/order');
var {orderController} = require('./controllers/orderController');
var app = express();
app.use(bodyParser.json());
app.get('/orders', (req, res) => {
orderController.listAllJson().bind(orderController);
});
app.listen(3000, () => {
console.log('Started on port 3000');
});
module.exports = {app};
When I hit my /orders route using postman I get:
TypeError: Cannot read property 'listOrderJson' of undefined error.
I added the 'bind' part to the function call after searching here on stack overflow a ton, but it didn't help. What am I doing wrong here?
orderController is { listAllJson: fn } so you can simply destructure and use it.
var express = require('express');
var bodyParser = require('body-parser');
var fs = require('fs');
var schedule = require('node-schedule');
var {mongoose} = require('./db/mongoose');
var {Order} = require('./models/order');
var {listAllJson} = require('./controllers/orderController');
var app = express();
app.use(bodyParser.json());
app.get('/orders', listAllJson);
app.listen(3000, () => {
console.log('Started on port 3000');
});
module.exports = {app};
Also minor note use res.json({"Here": "something"}); it does the stringifying and set the headers.
I have created a folder testint
My testint/app.js having following code
const express = require('express'); const path = require('path');
const bodyParser = require('body-parser'); const cors = require('cors');
const passport = require('passport'); const mongoose = require('mongoose');
const app = express(); const port = 7000; app.use(cors());
app.use(bodyParser.json());
app.use('/users', users); //Not working
app.get('/',(req,res) => {
res.send("Invalid Endpoint");
});
app.listen(port, () =>{
console.log('Server started on port '+ port);
});
testint/routes/users.js contains :
const express = require('express'); const router = express.Router();
res.send('Authenticate');
router.get('/register',(req, res, next) => {
res.send('REGISTER');
});
module.exports = router;
If I run http://localhost:7000/users/register
Am getting :
Cannot GET /users/register
I dint know where am wrong and am new to node any help will be appreciated.
I got solution. I didn't include
const users = require('./routes/users');
in app.js
and res.send('Authenticate'); in users.js is not required for instance.
I just want to capture the response error from a middleware function, it works if I write the code as follows:
var express = require('express');
var expressValidator = require('express-validator');
var app = express();
var bodyParser = require('body-parser');
var router = require('./routes');
//monk.mongoList();
app.use(bodyParser.urlencoded({extented:true}));
app.use(bodyParser.json());
app.use(expressValidator([]));
var port = process.env.PORT || 8978;
router.get('/',function(req,res,next) {
var error = Error('Article is not found');
next(error.message);
return res.send("Hello World!");
});
app.use(function(err,req,res,next) {
console.log(err + "TET");
})
app.listen(port);
but I want to separate the following code:
app.use(function(err,req,res,next) {
console.log(err + "TET");
})
and use it as follows:
app.js
var express = require('express');
var expressValidator = require('express-validator');
var app = express();
var bodyParser = require('body-parser');
var router = require('./routes');
//monk.mongoList();
app.use(bodyParser.urlencoded({extented:true}));
app.use(bodyParser.json());
app.use(expressValidator([]));
var port = process.env.PORT || 8978;
var test = require('./util/test')
app.use(test.logger);
app.use('/',router);
app.listen(port);
console.log('test node API ' + port );
util/test.js
module.exports.logger = function (err, req, res, next) {
console.log('LOGGED')
next()
}
/routes/index.js EDIT: I just edited the /routes/index.js file to make it more simple
var express = require('express');
var router = express.Router();
var url = require('url');
router.get('/api', function(req, res, next) {
var err = "this is error";
var error = Error (err)
var data = { data: "Succuss"}
if (err) {
next(error.message)
res.json({message:err})
}else {
res.json(data);
}
});
module.exports = router;
When add the above code, nothing appear in the console.