-1

I'm using request-promise to request two JSON data files which exist locally in my local project directory folder. ie:

enter image description here

However, I am getting a 500 internal server error, when trying to pass the data to the view and my node console outputs 'Error: Invalid URI "/"',

Please see below:

server.js

    let express = require('express');
    let app = express();
    let path = require('path');
    const rp = require("request-promise");

    //STORE PATH for local JSON files on variables
    let guest = require('./public/data/Companies');
    let hotel = require('./public/data/Guests');

    app.set("port", process.env.PORT || 5000);

    //GET JSON
    //Question: Is it okay to pass uri:guest
    app.get('/data', function(req, res) {
        Promise.all([rp({uri: guest, json: true}), rp({uri: hotel, json: true})]).then(function([hotels, guests]) {
            //res.json({hotels, guests});
            res.send({hotels, guests});
            console.log(hotels, guests);
        }).catch(function(err) {
            console.log(err);
            res.status(500).end();
        });
    });


    //CATCHALL
    app.get("/*", function(req,res){
        let file = req.params[0] || "/views/index.html";
        res.sendFile(path.join(__dirname, "/public/", file));
    });

    //SET PORT
    app.listen(app.get("port"), function(){
        console.log("Listening on port: " , app.get("port"));
    });

then on client.js:

$(function() {
    $.ajax({
        type: "GET",
        url: "/data",
        success: function (res) {
            console.log(res);
        }
    });
});
Jonca33
  • 3,333
  • 7
  • 25
  • 35

2 Answers2

2

Why do you use request to get the data? Why don't you use the filesystem module from Node.js (fs) to get the data? When you call rp(), you should pass an absolute URI and not a local path.

To use it in your code, you need to "promisify" the readFile function:

let readFileAsAPromise = function(filename){
  return new Promise(function(resolve, reject) {
    fs.readFile(filename, (data, err) => {
      if(err) reject(err);
      resolve(data)
    })
  })
}

You can then you Promise.all.

Olivier Liechti
  • 3,138
  • 2
  • 19
  • 26
1

Why aren't you simply returning the variables?

I mean:

app.get('/data', function(req, res) {
    res.send({hotels, guests}); 
});