i'm reading the book 'Node.js for PHP Developers'. I have created a NodeJS Web Server and it receives requests and gives response too. But whenever I access a PHP file to reroute it to a JS file (requirement it is), my browser automatically downloads the PHP file.
Here's my JS code, according to which it also downloads JS files(e.g. 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's my PHP file if it matters
<?php
echo "ASD";
?>
I know it feels like a really dumb question, but I can't figure out why that happens.
Browsers tested: Chrome and Firefox.
UPDATE Couldn't figure out the exact problem neither could replicate the problem - but this is my latest code if anyone wants to reroute a requested PHP file to a JS file and serve it(the 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');
If you want to check if a PHP page can be rendered without actually rendering 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 output that the PHP file was successfully accessed.
Once you get a better handle on node, you'll 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 then wanted to display the php, you could use php-node to render php in node.js.
It seems that you don't have Apache (or some other server) or PHP configured. The request has to go to the PHP script first. So you would have to hit localhost:80/file.php and then in the PHP script redirect to localhost:1337/file.js.
A better suggestion for what you want to do is actually reverse proxy from Apache to Node.js and then have Node.js read the path.