0

I'm encountering a problem with the express routes. Here's my case: I have a node js app with the following code in app.js

var express = require('express');
var app = express();
var path = require('path');

var bodyParser = require('body-parser');

app.use(bodyParser.urlencoded({
  extended: false
}));
var cfenv = require('cfenv');

// request module provides a simple way to create HTTP requests in Node.js
var request = require('request');

var routes = require('./routes')(app);

app.get('/', function (req, res) {
 res.sendFile(path.join(__dirname + '/public/index.html'));
});

var appEnv = cfenv.getAppEnv();

// compose for mysql code
var dbcontroller = require('./controller/compose-mysql-connection');
dbcontroller.databaseconnection();

const util = require('util');
// and so is assert
const assert = require('assert');

var mysql = require('mysql');

var appEnv = cfenv.getAppEnv();

// Within the application environment (appenv) there's a services object
var services = appEnv.services;

// The services object is a map named by service so we extract the one for Compose for MySQL
var mysql_services = services["compose-for-mysql"];

// This check ensures there is a services for MySQL databases
assert(!util.isUndefined(mysql_services), "Must be bound to compose-for-mysql services");

// We now take the first bound Compose for MySQL database service and extract it's credentials object
var credentials = mysql_services[0].credentials;

var connectionString = credentials.uri;

// set up a new connection using our config details
var connection = mysql.createConnection(credentials.uri);


//reading from the database
app.get("/read_fb_info", function(request, response) {

  connection.query('SELECT * FROM fb_info_table ORDER BY name ASC', function (err, result) {
    if (err) {
      console.log(err);
     response.status(500).send(err);
    } else {
      console.log(result);
     response.send(result);
    }

  });
});

app.use(express.static(__dirname + '/public'));
// start server on the specified port and binding host
app.listen(appEnv.port, '0.0.0.0', function() {
  // print a message when the server starts listening
  console.log("server starting on " + appEnv.url);
});

Then, in the routes folder I have a file with other two routes I use into the application. Once the index page is loaded I have two button:

<body>
    <div class="container">
      <h1>External API Usage</h1>
      <h3>LinkedIn</h3>
        <a href='/info/linkedin'>
          <img src="/images/LinkedIn_image.png" class="img-rounded" alt="LinkedIn" width="150" height="150">
        </a>
      <h3>Facebook</h3>
        <a href='/info/facebook'>
          <img src="/images/Facebook_image.png" class="img-rounded" alt="Facebook" width="150" height="150">
        </a>
    </div>

To handle routes I created an index.js file in the routes folder which includes the following:

retrieveFacebookUserInfo = function() {
    var deferred = Q.defer();

    var propertiesObject_FB = { id:'id', name:'name', access_token:'access_token' };

    request({url:'https://graph.facebook.com/', qs:propertiesObject_FB}, function(err, response, body) {
      if(err) {
            deferred.resolve(null);
      }
        else {
            var fb_json = JSON.parse(body);
          console.log("Get response: " + response.statusCode);
            console.log(fb_json);

            //storing information to db
            dbcontroller.writingtodb();

            deferred.resolve(fb_json);
        }
    });

    return deferred.promise;
};
app.get('/info/facebook', function(req, res){
        retrieveFacebookUserInfo().then(function(result){
                res.render('facebook.ejs', {
                    title : 'Facebook information',
                    fb_obj: result
                });

            });

        });

  app.get('/info/linkedin', function(req, res){
        retrieveLinkedInUserInfo().then(function(result){
            res.render('linkedin.ejs', {
                title : 'LinkedIn information',
                headline_linkedin: result.headline
            });
        });
  });

If I try to open the second one (/info/facebook) at first e then the first one (/info/linkedin) it doesn't load the page related of /info/linkedin route. It shows this message:

404 Not Found: Requested route ('linkedin-demo-app.eu-gb.mybluemix.net') does not exist.

Do you guys know what is this kind of problem? It seems like it doesn' recognize and find the route again. Thanks in advance

g_tech
  • 251
  • 1
  • 4
  • 13
  • Where's a route handler for `'/info/linkedin'` or `'/info/facebook'`? I don't see a route for either. – jfriend00 May 22 '17 at 02:42
  • Yes, there are sorry. I just edited the question - I have a file with all the routes in the routes folder. – g_tech May 22 '17 at 09:10
  • One more thing, I also added the function "retrieveFacebookUserInfo" in the code above. As you can see, if I comment the function "dbcontroller.writingtodb();" everything works fine, otherwise I have issues with the routes. You understand what is the problem? – g_tech May 22 '17 at 13:11
  • Well, perhaps `dbcontroller.writingtodb()` is throwing an exception or causing some other problem. If commenting that out, makes the problem go away, then the problem is probably in that function, but you don't show us that code so there's not much else we can say. Also, if you get an error from the `request()`, you will resolve the promise with `null` which will then cause an exception when you try to access `result.headline` in the render. Error handling is not correct here at all. – jfriend00 May 22 '17 at 21:15

1 Answers1

1

You simply don't have route handler for these two paths. You need to create them like you did for your /read_fb_info path:

app.get("/info/linkedin", function(request, response) {
  //do somenthing and send your response
});

app.get("/info/facebook", function(request, response) {
  //do somenthing and send your response
});
JSEvgeny
  • 2,550
  • 1
  • 24
  • 38
  • Ok i see now. I think you don't need to provide a file extension inside render function. Try to simply write `res.render('linkedin', {...` instead of `linkedin.ejs` – JSEvgeny May 22 '17 at 09:19
  • You can also try to only console.log something inside your route handler so you can check that you at least "get inside" your route – JSEvgeny May 22 '17 at 09:25
  • Ok, I also added the function "retrieveFacebookUserInfo" in the code above. As you can see, if I comment the function "dbcontroller.writingtodb();" everything works fine, otherwise I have issues with the routes. You understand what is the problem? – g_tech May 22 '17 at 13:11
  • the problem is that at the first time I got into route and if I try again not – g_tech May 22 '17 at 15:23