Home > Back-end >  Can node.js request php file as its endpoint on the same file system, not an http request?
Can node.js request php file as its endpoint on the same file system, not an http request?

Time:10-21

I am new to node.js and am building a chat appication that is running inside an existing PHP application. I am using expressjs and also postman-request module. I can easily hit absolute urls but when I try to request a file that lives on my own file system, it fails. I have watch tutorials and read the docs and it seems like the only examples ever shown are how to hit external urls.. I can't imagine that it is not possible to hit files that reside on your own file system.

Here is code below: (in my main index.js server file)

const request   = require('postman-request');
const url = 'utils/config.php'; // this file merely echos out a json encoded string.
request(url, function (error, response, body) {
      console.log('error:', error); // Print the error if one occurred
      console.log('statusCode:', response && response.statusCode); // Print the response 
      console.log('body:', body); 
    });

Here is the error message: error: Error: Invalid URI "utils/config.php"

This is the file structure:

-node_modules
-public
-src
    -utils
        -config.php
  index.js (start for node.js - inside src folder)

Any help would be appreciated.

CodePudding user response:

Requesting refers to requesting a file from a webserver. Here, you're trying to request a file path, while the computer thinks is a non-existent URL. The PHP file is just text. It doesn't mean anything to the computer, and the PHP interpreter is what runs the PHP code. You aren't running a PHP server in this case, and you're requesting a file path, not a URL.

You have to start a PHP server first, using the php command. Make sure to pass in the URL (for example, localhost:8080/config.php), and not the file path.

If you wanted to do it entirely from the Node script, you could start a server, request the URL, and then stop the server. It would be possible to use the spawn function from the built-in child_process module (refer here). You could also use exec, but this is probably unnecessarily harder.

  • Related