File path issue using Node.js

150 views Asked by At

I'm deploying a node.js based application to IBM's Bluemix and have added a few features to one of the samples they provide. I've added an additional javascript file that makes an ajax call to PHP, but the PHP file is coming back as not found because my path is incorrect. I've tried putting the file everywhere and it's just not being found. I'm thinking (as a total node noobie) that I'm missing some mysterious configuration or something.

In the main directory (among other things), the structure is like this:

-- views
   - index.ejs (this is the main displayed code)
-- public
   - js
     - custom.js (my added file)
     - all the other necessary js files
   - css
   - img
   - php - I added this directory
     - get-twitter.php - I added this...custom.js makes an ajax call here

In custom.js, I have this:

$("#get-twitter").click(function(event) {
    handle = $('#twitter-handle').val();
    $.ajax({
        url: 'php/get-twitter.php',
        type: 'POST',
        dataType: 'JSON',
        data: {
          handle: handle,
            },
        success: function(data) {
        console.log(data);
        $.each(data, function(index, val) {
           console.log(val.text);
        });
        }
 });
  });

When I try to make this call, the file isn't found, but the path is this: https://myapp.mybluemix.net/php/get-twitter.php It should be in views/php/get-twitter.php, but I'm guessing this is a configuration issue on my end.

I've tried every iteration of this: url: 'php/get-twitter.php', and put the PHP file in every directory and nothing is working.

What am I missing here?

2

There are 2 answers

0
posit labs On

There is no way to run PHP scripts from node. You will need to set up a server that supports PHP, and make your requests there. One option would be Apache.

Realistically, you probably don't want to set up an entire server for the purpose of running a single PHP script. A more reasonable solution would be to port the PHP script to run on Node. There are many packages for twitter API integration on NPM (e.g. the twitter module).

0
AudioBubble On

If the server has PHP installed, then you can try to use exec to run the PHP file using the command line interpreter and get the output. Obviously you need to refactor your code to work with arguments passed by shell ($args) and display a JSON response that will be catched by node. For example:

exec('php -f /project/file.php', function (err, out) {
  if (!err) {
    const output = JSON.parse(out);
    // do something with the object
  }
});

As @positlabs said, keep the things simpler and port the script to JavaScript.