express routes do not load again

91 Views Asked by At

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

1

There are 1 best solutions below

4
On

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
});