Peter Boomsma Peter Boomsma - 3 months ago 12
Node.js Question

Retrieve data from MySql db through express and Angular

I'm trying to retrieve some data from my MySql database to my Angular controller through node/express but I'm having some trouble with the routing.

In the angular controller I have a load function that does a get request:

$scope.load = function () {
$http.get('/users').
success(function(data, status, headers, config) {
console.log('success');
$scope.todos = data;
console.log(data);
console.log($scope.todos);

}).
catch(function(data, status, headers, config) {
console.log('catch');
console.log(status);
console.log(data);
});
};


In my app.js I have:

var users = require('./routes/users');
app.use('/users', users);


And in my routes/users.js file I have:

var express = require('express');
var router = express.Router();
var pool = require('../connection');

/* GET users listing. */
router.get('/users', function(req, res, next) {

pool.getConnection(function(err, connection){
connection.query('SELECT * FROM `users` WHERE `first_name` = "Kees"', function(err, results){
if(err) {
throw err;
}else{
console.log(results);
}
});

connection.release();
});
});

module.exports = router;


When I fire the load() function in my view the app.js log returns:


GET /users 404 54.369 ms - 1846


And the browser shows:


GET http://localhost:3000/users 404 (Not Found)

catch

Object {data: "", status: 404, config: Object, statusText: "Not Found"}


What's the correct way to retrieve the data through Express?

Answer

In your app.js you have already set up the route for any calls to /users. That means that all the http requests in your users.js-file already has that in the url. So this:

router.get('/users', function(req, res, next)

actually is called from example.com/users/users.

Just write it like this instead:

router.get('/', function(req, res, next)
Comments