Unable to get routes working in Nodejs - node.js

The server.js code is this one after running the node server.js command
i am able to access the http://localhost:8080/ and getting the json correctly
{"error":false,"data":[{"id":1,"task":"Find bugs","status":1,"created_at":"2016-04-10T18:20:40.000Z"},{"id":2,"task":"Review code","status":1,"created_at":"2016-04-10T18:20:40.000Z"},{"id":3,"task":"Fix bugs","status":1,"created_at":"2016-04-10T18:20:40.000Z"},{"id":4,"task":"Refactor Code","status":1,"created_at":"2016-04-10T18:20:40.000Z"},{"id":5,"task":"Push to prod","status":1,"created_at":"2016-04-10T18:20:50.000Z"}],"message":"Todos list."}
but when i try to access the http://localhost:8080/secret i am getting "Cannot GET /secret " error. My server.js file is this one
const express = require('express');
const app = express();
const mysql = require('mysql');
const bodyParser = require('body-parser');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended:true
}));
const mc = mysql.createConnection({
host:'localhost',
user : 'root',
password : '',
database : 'task'
});
mc.connect();
// Retrieve all todos
//default route
app.all('/',function(req,res,next){
mc.query('SELECT * FROM tasks', function (error, results, fields) {
if (error) throw error;
return res.send({ error: false, data: results, message: 'Todos list.' });
next()
});
});
app.use('/secret', function (req, res, next) {
console.log('Accessing the secret section ...')
next() // pass control to the next handler
})
app.listen(8080,function(){
console.log('Node app is running on port 8080');
});
Any help will be much appreciated

Your implementation right now seems incomplete. You should check out the express.Router documentation (check out the very bottom of the page).
The use method you are trying to use should include at least a router.get('/', function (req, res) {} ); implementation. Alternatively, you could replace use with get or all and it would work.
Good luck!

You should use get instead of all, and the next function is not required. try the below method.
app.get('/', function (req, res) {
mc.query('SELECT * FROM tasks', function (error, results, fields) {
if (error) throw error;
return res.send({ error: false, data: results, message: 'Todos list.' });
});
});

Related

when call router.post method from url get error 404 not found in express.js

I have got a problem with Express, I am trying to use the app.post() function but it's not working and I don't know why...
Even though I have included the bodyParser()...
It returns 404 page not found error
var express = require('express');
var MongoClient = require('mongodb').MongoClient;
var router = express.Router();
router.post("/hello",(req, res) => {
res.send('POST CALL');
});
/* GET home page. */
router.get('/', function(req, res, next) {
MongoClient.connect('mongodb://localhost:27017/nicky', function (err, client) {
if (err) throw err
var db = client.db('nicky')
db.collection('student').find().toArray(function (err, result) {
if (err) throw err
res.send(JSON.stringify(result));
})
})
});
module.exports = router;
GET is working properly, but POST is not.
I am not sure how rest of your code looks, but I have copied your provided snippet and it works this way:
express-post.js:
const express = require('express');
const router = express.Router();
// curl -X POST http://localhost:3000/bar/hello
router.post("/hello",(req, res) => {
res.send('It is POST');
});
// curl -X GET http://localhost:3000/bar/hi
router.get('/hi', function(req, res, next) {
res.send('It is GET');
});
module.exports = router;
express-post-server.js:
const express = require('express');
const bar = require('./express-post');
const app = express();
// curl -X GET http://localhost:3000/foo
app.get('/foo', function (req, res, next) {
res.send('This is foo GET!');
});
// register
app.use('/bar', bar);
app.listen(3000);
For complete running example clone node-cheat and run node express-post.
Maybe you haven't required and initialized body-parser!
Just confirm once if you have included this:
const bodyParser = require('body-parser');
// support parsing of application/json type post data
app.use(bodyParser.json());
//support parsing of application/x-www-form-urlencoded post data
app.use(bodyParser.urlencoded({ extended: true }));
May be you forgot to use
app.use('/',require('import route here'));
in main app.

Only able to access one route from routes hierarchy

I'm attempting to access a route directly from a request, even though another subfolder works the other does not. Repeatedly throwing 404 errors. /api/getPostList works but /post/ or /post/:title doesn't work.
I've restructured the code, attempted to change it from a get request to a post request, added /post/:title to access an individual post or without a / to access the main list.
Server.js contains
app.use('/', Routes);
routes/index.js contains
const router = require('express').Router();
const posts = require('./posts');
const api = require('./api');
router.use('/post', posts);
router.use('/api', api);
module.exports = router;
routes/api/index.js contains
Api.get('/getPostList', (req, res) => {
PostModel.find(function (err, post) {
if (err) return console.log('error: ' + err);
return res.json({ postList: post});
});
console.log("Attempted to get post list on /getPost/ route: " + ++postRouteCnt);
});
Api.get('/getPost/:title', getPost);
module.exports = Api;
routes/post/index.js contains
const Posts = require('express').Router();
const post = require('./post');
const PostModel = require('../../../server/models.js');
let postRouteCnt = 0;
Posts.get('/', (req, res) => {
PostModel.find(function (err, post) {
if (err) return console.log('error: ' + err);
return res.json({ postList: post});
});
console.log("Attempted to get post list on /post/ route: " + ++postRouteCnt);
});
Posts.get('/:title', post);
module.exports = Posts;
When calling /post/ I get a 404 Cannot GET /post/ when I should receive the json response.
EDIT:
Folder structure
Server/
routes/
api/
index.js
getPost.js (for individual post)
posts/
index.js
post.js (for individual post)
server.js
Base on your structure folder, I try to write code with simple code
App.js :
const express = require('express')
const app = express()
const port = 3000
const Routes = require('./routes/posts/index.js');
app.use('/', Routes);
app.listen(port, () => console.log(`Example app listening on port ${port}!`))
.routes/ posts/ index.js :
const express = require('express');
const router = express.Router();
const postController = require('./post');
// GET /
router.get('/posts', postController.getPosts);
module.exports = router;
.routes/ posts/ post.js :
exports.getPosts = (req,res) => {
res.send('test');
}
Try input http://localhost:3000/posts and its work
You can write any logic in .routes/ posts/ post.js :
try changing it like this
Posts.get('/', (req, res) => {
PostModel.find(function (err, post) {
if (err) throw err;
res.send({ postList: post});
});
console.log("Attempted to get post list on /post/ route: " + ++postRouteCnt);
});
now try this url
/post/

How to fetch data in mongoDB to show in localhost (Node.js)

I am working on to do list app using mongoDB and node.js. Basically you type what you want to do then click add. I successfully connected the database but it doesn't show the text that's in the database. It shows only the bullets in the localhost.
Here's the code:
app.get('/', function(req, res) {
db.collection('list').find().toArray(function (err, result) {
console.log(result);
if (err) {return};
console.log(err);
res.render('index.ejs', {list: result})
});
});
app.post('/', function(req, res){
console.log(req.body);
db.collection('list').save(req.body, function(err, result) {
if (err) {return};
console.log(err);
console.log('saved')
res.redirect('/');
})
})
I have validated the code you posted and have revised it slightly with comments.
I hope this helps but it seems that the fault might be in the res.render method that is being used. Please refer to the following code:
// Requires
var express = require('express');
var bodyParser = require('body-parser');
var MongoClient = require('mongodb').MongoClient;
// Instantiation
var app = express();
var mongopath = "mongodb://localhost:27017/BitX";
// Port number the REST api works on
var portnum = 7500;
// MongoDB object
var db = null;
MongoClient.connect(mongopath, function(err,ldb){
db = ldb;
});
// Implement Body Parser
app.use(bodyParser.urlencoded({
extended: false
}));
app.use(bodyParser.json());
// Start the REST service
var server = app.listen(portnum, function() {
var host = server.address().address;
var port = server.address().port;
console.log("Content Provider Service listening at http://%s:%s", host, port);
});
// Default route
app.get('/', function(req, res) {
// Find all items in orders and send back results to a front end
db.collection('orders').find().toArray(function (err, result) {
res.send(result);
// Consider that the rendering engine may not be functioning correctly
// SEE MORE: https://stackoverflow.com/questions/21843840/what-does-res-render-do-and-what-does-the-html-file-look-like
//res.render('index.ejs', {list: result})
});
});
// Accept a post on the root
app.post('/', function(req, res){
//Save into orders
db.collection('orders').save(req.body, function(err, result) {
res.send(true);
//res.redirect('/');
});
});
For additional information on the res.render method please have a look at:
What does "res.render" do, and what does the html file look like?
- if you have not already.
Hope it helps!

Cannot POST /userslist in node js

I am very new to node js. I have made an application, where when admin logs in, it is showing 'Cannot POST /userslist', but once I refresh the page, it is fetching the userslist, following is the routing code for admin-
admin.js-
module.exports = function(app)
{
app.get('/adminedit', function (req, res) {
res.render('adminedit', { });
});
app.get('/userslist', function (req, res) {
res.render('userslist', { });
});
}
i think the best way to achieve your goal (using express) is:
create a single service (called for example listUsers) in this way:
var express = require('express');
var router = express.Router();
router.post('/', function(req, res, next) {
User.find(function (err, users) {
if(err) return res.json({success: false, message: err});
res.json({success: true, userlist: users});
)};
});
module.exports = router;
then you can use this service in app.js in this way:
var userListService = require('./routes/listUsers');
app.use('/listUsers', userListService);
at this point if you try to call in POST /listUsers, everything should work fine.

NodeJS/Express GET exit status of external application

I am pretty new to NodeJS and this is my first time with Express 4, I'm trying to build a simple RESTful front-end around a command-line application. There will ultimately only be one GET and one POST necessary, with the POST handling about 3 or 4 different parameters. The GET should call the command-line application with all default parameters, which is basically just a status check and return the exit status upon completion. The POST will pass along POST parameters on the commandline. I know that this basically calls for an asynchronous call, like child_process.execFile(), but I can't seem to figure out how to actually return the response from within the callback function.
This is the tutorial I used as a starting point, omitting the mongoose dependency, because I have no need for MongoDB, so I basically just followed it up to the point where you start the server. At this point, I'm pretty lost. I always hate writing async code...
var express = require('express'); // call express
var app = express(); // define our app using express
var bodyParser = require('body-parser');
var child_process = require('child_process');
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
var port = process.env.PORT || 8080; // set our port
var router = express.Router(); // get an instance of the express Router
router.get('/', function(req, res) {
res.json({ message: 'hooray! welcome to our api!' });
});
router.get('/myapp/status', function(req, res) {
console.log(req.user);
child_process.execFile(
'casperjs',
['myfile.js', '--cmd="Status"', '--user="myuser"', '--pass="#mypass"'],
null,
function(response) {
// ???
}, res);
});
app.use('/api', router);
app.listen(port);
console.log('Magic happens on port ' + port);
You can try the following:
router.get('/myapp/status', function(req, res) {
console.log(req.user);
child_process.execFile(
'casperjs', //command
["myfile.js --cmd=Status --user=myuser --pass=#mypass"], // args
function(err, stdout, stderr) { //callback
if (err) {
return res.status(500).send(err);
}
res.send(stdout); // to send response to client
});
});

Resources