Browser automatically downloads PHP files - javascript

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.

Related

Node.js launches html to localhost:8000, how can I call a .mp3/.mp4 file in that html file

I am using node.js to launch an HTML file to display on the localhost:8000.
None of the media files that the HTML calls work. The HTML works fine when I launch it from the windows icon. I assume that I need to change how the media files are called.
I have tried moving the media files into the native folder.
//This is how I call the HTML.
var http = require('http'),
fs = require('fs');
fs.readFile('./index.html', function (err, html) {
if (err) {
throw err;
}
http.createServer(function(request, response) {
response.writeHeader(200, {"Content-Type": "text/html"});
response.write(html);
response.end();
}).listen(8000);
});
//This is how the media file is called in the HTML (index.html).
<audio id="Whistle" src="C:\Site\Whistle.mp3" preload="auto" ></audio>
There is javascript in the HTML file that "plays" the file.
I am not getting any error messages from node.js or the web browser. It just isn't calling the file and moving on.
I am not getting any error messages from node.js or the web browser
That's surprising because C:/... isn't a valid path. Rember that it is resolved on the client side, and there you don't have access to the servers file system. You also don't have access to the local file system the browser is running on for security reasons.
For sure you could send a request to the server instead, then the server could answer with a sound file.
Read on
Also make sure you know the basics

Browser downloads the html file instead of opening

I have created a server with Node.JS express where I open html file in public folder.
app.use(express.static(__dirname + '/public'));
app.listen(8080);
I have done this before without any problems. But in this project when I try to open the server in 127.0.0.1:8080 it automatically downloads the index.html file. I tried it with different browsers but result was same.
UPDATE
I could open html file in Edge. But it was very very slow like it is processing some thing. And it got stuck when I send a request to the server.
I tried opening the HTML file separately with the browser it works without any problem.
And tried giving another html file location, result was same.
I do not know what is the exact problem here. But I got to know that it has to do something with content type as td-lambda mentioned in the comments. So I found a solution like this.
var express = require('express');
var app = express();
var server = app.listen(8080);
app.set({
'Content-Type': 'text/html'
});
app.use(express.static(__dirname + '/public'));
And this solved my problem.

Joining together nodejs html5 and canvas

I've got a very simple html5 game on one side. Opening the game's html file directly with my browser makes the game work just fine. On the other side, I have an html sever made with node.js that can serve html text normally (tags like < /br> < p> and so on).
But when I tell the server to display my game as html text priting the whole html file, the canvas fails to render (although the title does). So now I'm kind of lost on what's happening and why I'm not able to link those two things together. Here's a simplified version of my server's code:
var http = require('http');
var fs = require('fs');
var index = fs.readFileSync('index.html');
http.createServer(function(req, res) {
res.writeHead(200, {'Content-Type': 'text/html'});
res.write(index);
res.end()
}).listen(7777);
So, what am I doing wrong here? Should this work normally? Am I missing something?
It seems just as if the javascript was sent as plain text and the code was never actually executed.
Your server serves only the index.html so if that page depends on any other resources it will fail to work as requests to CSS and JS files will fail. Try out e.g. this:
$ npm -g install simplehttpserver
$ simplehttpserver /path/to/your/folder
Then go with browser to
http://localhost:8000/index.html

Using non-inline javascript in HTML via node.js

I'm very new to node.js so I apologize if this is a poor question. I have a simple HTTP server here:
var http = require('http');
http.createServer(function (request, response){
response.writeHead(200, {"Content-Type":"text/html"});
// response.write("<html><head><script type = 'text/javascript'>alert('hello');</script></head></html>");
response.write("<html><head><script type = 'text/javascript' src = 'alerter.js'></script></head></html>");
response.end();
}).listen(8000);
console.log("Server has started.");
alerter.js contains the one line:
alert("hello");
Why does using the commented-out line properly cause an alert, but calling alerter.js does nothing?
Your problem, as Paul and Timothy pointed out, is that when the browser gets your html with an external reference, it goes back to the server and asks it for alerter.js, expecting to have the script delivered to it. However, your server always sends out the same thing regardless of what the request asks for, so the browser never gets the script.
You need to change your server to, at the very least, handle a request for alerter.js. Realistically, I'd use something like Connect's static file handler to do that; put all the assets like scripts, stylesheets and images in a directory (usually called "public") and tell the static handler to serve them from there.
You are missing a ' to end the type attribute.

How to use socket.io to communicate with another server when the actual page is being served by a localhost server?

I'm serving my page through localhost (XAMPP, Apache), and on my friend's physical server I run a node.js server that is used for communication with the page (a game).
This is the node.js server code:
var io = require('socket.io').listen(1235);
io.sockets.on('connection', function (socket)
{
socket.on("start", function (data)
{
console.log(data);
});
});
It runs without any errors, but I don't know how to include the socket.io code into my webpage! How do I do that?
Include a script tag in your page:
<script src="http://[YOUR IP]:1235/socket.io/socket.io.js">
And it will be served by your node.js server.
Apart from that, you can just follow the examples on socket.io, e.g.:
var socket = io.connect("http://[YOUR IP]:1235");
socket.emit("start", "LET'S GO!");
2 Options. Per the documentation, you can do a JavaScript src pointing at your node server:
<script src="http://url.to.node.com/socket.io/socket.io.js"></script>
Or you can include it manually, grabbing it from the Git repo at https://github.com/LearnBoost/socket.io-client/blob/master/dist/socket.io.js

Categories

Resources