The browser downloads PHP files automatically

I am reading the book "Node.js for PHP Developers". I created a NodeJS web server and it receives requests and gives a response. But whenever I access the PHP file to redirect it to a JS file (this is required), my browser downloads the PHP file automatically.

Here is my JS code according to which it also loads JS files (for example when I access localhost: 1337 / first.njs)

var http = require('http');
var url = require('url');
var file = require('./first.njs');

http.createServer(function(req, res) {
if(url.parse(req.url).pathname == 'first.php')
    file.serve(req, res);
else
    res.end('The file doesn\'t exist');
}).listen(1337, '127.0.0.1');

console.log('Server is running on 1337');

      

And here is my PHP file if it matters

<?php
  echo "ASD";
?>

      

I know this sounds like a really stupid question, but I can't figure out why this is happening.

Browsers tested: Chrome and Firefox.

UPDATE Unable to figure out what the exact problem is, cannot replicate the problem - but this is my final code, in case anyone wants to redirect the requested PHP file to a JS file and execute it (JS file)

var http = require('http');
var url = require('url');
var file = require('./first.njs');

http.createServer(function(req, res) {
if(url.parse(req.url).pathname == '/first.php')
    file.serve(req, res);
else
    res.end('File not found');
}).listen(1337, '127.0.0.1');

console.log('Server is running on 1337');

      

+3


source to share


3 answers


If you want to check if a PHP page can be rendered without passing it to the page, you can use an ajax request in JavaScript / jQuery.

    $.ajax({
        type: "POST",
        url: 'YOUR PHP FILE PATH',
        success: function (dataCheck) {
            // file was accessed
        }
    });

      



Inside your success function, you can deduce that the PHP file was successfully accessed.

+2


source


Once you get the best descriptor on node, you probably want to use expressjs, take a look at expressjs routing .

app.get('/first.php', function(req, res){
    res.send('You accessed first.php!');
});

      




If you want to render php you can use php- node to render php to node.js.

+1


source


It seems like you don't have Apache (or another server) or PHP. The request must go to the PHP script first. So you will need to hit localhost: 80 / file.php and then redirect to localhost: 1337 / file.js in PHP script.

The best suggestion for what you want to do is actually reverse proxy from Apache to Node.js and then Node.js read the path.

0


source







All Articles