How to access to the application through browser? - node.js

How can I access my server through the browser once I've set up the server ?
In PHP I simply have to put my files in the www/ folder and then go to http://127.0.0.1/index.php, but how can I do that with NodeJS ?
My server's code is from a tutorial :
var app = require(‘express’).createServer();
app.get(‘/’, function(request, response){
response.send(‘Hello Web Designer’);
});
app.listen(8888);
But whenever I go to http://127.0.0.1:8888/ i get a "Problem loading the page". So either my server is not running correctly (hard to tell when the NodeJS console shows "...") or I am not accessing it correctly.
What can I do please ?

you have to send a http head and end the response.
Try this code.
var http = require('http');
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.write('hello world');
res.end();
}).listen(8888);
(Pseudo Code)
Also don't use any frameworks to learn how node works.
You can run you index.js now and call localhost:8888

Did you start the server? The apache server runs php, in the nodejs world, there is a javascript runtime that needs to be started.
Try node server.js from the command line (or whatever your file is called) to get it to listen and serve incoming requests.

Related

Browser downloads the file instead of showing html

I have developed MERN app in my local system. I am trying to host it AWS-EC2 (Free Tier).
Never thought deploying would be so painful.(Well, i am beginner to Node. Earlier i have worked with php. I found it easier to integrate)
I referred this article to install Node and Express. Node is successfully installed. I created sample file 'test.js' with following code:
var http = require('http');
var port = 9000;
http.createServer(function(req,res){
res.writeHead(200,{'Content-Type':'test/plain'});
res.end('Hello world!\n');
}).listen(port);
console.log('Listening on port',port);
After executing
node test.js
the browser downloads a file with no extension. Opened in editor and it has 'Hello World' in it. Nothing else. I am pretty sure i have followed all steps properly. But still i ended up 'Downloading the file'
Can anyone help me with this issue?
BONUS QUESTION : How do i deploy MERN app in AWS EC2?
Have a nice day
Thanks
try this (you forgot to add the listen callback, and a typo in content type):
var http = require('http');
var port = 9000;
http.createServer(function(req,res){
res.writeHead(200,{'Content-Type':'text/plain'});
res.end('Hello world!\n');
}).listen(port, err => {
if (err) throw err
console.log('Listening on port',port);
})
Use appropriate content type for your html page.
res.writeHead(200,{'Content-Type':'text/html'});
For a viewable html code, text/html should be set as content type instead of test/plain.

How to create a localhost in Node.js? And why mine is not working?

I'm not able to create a localhost for Node.js. Following are the thing I had completed:
I had created a file named server.js and the code is as follows:
var http = require('http');
http.createServer(function(request, respone){
respone.writeHead(200, {'Content-type':'text/plan'});
response.write('Hello Node JS Server Response');
response.end("Hello Sowmay Response ended");
}).listen(7000);
Then I had run this javascript script file on node.js cmd prompt as follows:
C:\Users\Guest\Desktop\First-Node>node server.js
After that I tried opening the local host on my windows PC from this link: http://localhost:7000
Result:
This site can’t be reached
localhost refused to connect.
Where I'm going wrong?
There is a mistake in your code.
I guess your console would output :
undefined has not a function "writeHead"
Becuase respone.writeHead(200, {'Content-type':'text/plan'}); lack a 's'.
Please use:
var http = require('http');
http.createServer(function(request, response){
response.writeHead(200, {'Content-type':'text/plan'});
response.write('Hello Node JS Server Response');
response.end("Hello Sowmay Response ended");
}).listen(7000);
and try again

Not able to run node.js program in command prompt

error on executing the programI am beginner to node.js .I have followed all the steps from the below blog:
http://blog.teamtreehouse.com/install-node-js-npm-windows
I got the node version and npm version too.
But not getting the output when I try to run the js file from cmd.
console.log('Node is installed!');
the content of the js file is mentioned in the above line.
Please help me out!!
Thanks in advance
Its Seems there is no hello.js in c drive or in wrong directory
Goto any folder and make your hello.js and then navigate to that folder in cmd then write
node hello.js // .js is optional
in the picture above you can i receive error helloo cant find module becoz i dont have any file with name helloo.js
suppose your file is in D drive then goto D drive and wirte
Your can make simple hello.js server
//Lets re quire/import the HTTP module
var http = require('http');
//Lets define a port we want to listen to
const PORT=8080;
//We need a function which handles requests and send response
//Create a server
var server = http.createServer(function (request, response){
response.end('It Works!! Path Hit: ' + request.url);
});
//Lets start our server
server.listen(PORT, function(){
//Callback triggered when server is successfully listening. Hurray!
console.log("Server listening on: http://localhost:%s", PORT);
});

display html page with node.js

This is my first time with node.js. I get it to display the index.html, but it doesn't display the images on the site or anything else, it ONLY shows the basic html stuff. Here's how I set it up.
There's no apache, php or anything else on the server, just ubuntu, proftp and node(and curl and the other dependencies). I made the main directory for the node files /var/nodeFiles and the directory for the html/site files is /var/nodeFiles/www
so for my node server file I did it like this:
var http = require('http'),
fs = require('fs');
fs.readFile('/var/nodeFiles/www/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(80);
});
this works, but it ONLY shows the index.html file and NOTHING attached to it, so no images, no effects or anything that the html file should display. The files and directories are all correct, I've double checked and the permissions of the folders are correct. So what else do I have to do to get node to display the rest of the site?
I hope I've explained my self correctly, I was told this is the place to ask development questions.
Thank you for taking the time to read this.
but it ONLY shows the index.html file and NOTHING attached to it, so no images,
no effects or anything that the html file should display.
That's because in your program that's the only thing that you return to the browser regardless of what the request looks like.
You can take a look at a more complete example that will return the correct files for the most common web pages (HTML, JPG, CSS, JS) in here https://gist.github.com/hectorcorrea/2573391
Also, take a look at this blog post that I wrote on how to get started with node. I think it might clarify a few things for you: http://hectorcorrea.com/blog/introduction-to-node-js
Check this basic code to setup html server. its work for me.
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 did the trick for me:
var express = require('express'),
app = express();
app.use('/', express.static(__dirname + '/'));
app.listen(8080);
If your goal is to simply display some static files you can use the Connect package. I have had some success (I'm still pretty new to NodeJS myself), using it and the twitter bootstrap API in combination.
at the command line
:\> cd <path you wish your server to reside>
:\> npm install connect
Then in a file (I named) Server.js
var connect = require('connect'),
http = require('http');
connect()
.use(connect.static('<pathyouwishtoserve>'))
.use(connect.directory('<pathyouwishtoserve>'))
.listen(8080);
Finally
:\>node Server.js
Caveats:
If you don't want to display the directory contents, exclude the .use(connect.directory line.
So I created a folder called "server" placed index.html in the folder and the bootstrap API in the same folder. Then when you access the computers IP:8080 it's automagically going to use the index.html file.
If you want to use port 80 (so just going to http://, and you don't have to type in :8080 or some other port). you'll need to start node with sudo, I'm not sure of the security implications but if you're just using it for an internal network, I don't personally think it's a big deal. Exposing to the outside world is another story.
Update 1/28/2014:
I haven't had to do the following on my latest versions of things, so try it out like above first, if it doesn't work (and you read the errors complaining it can't find nodejs), go ahead and possibly try the below.
End Update
Additionally when running in ubuntu I ran into a problem using nodejs as the name (with NPM), if you're having this problem, I recommend using an alias or something to "rename" nodejs to node.
Commands I used (for better or worse):
Create a new file called node
:\>gedit /usr/local/bin/node
#!/bin/bash
exec /nodejs "$#"
sudo chmod -x /usr/local/bin/node
That ought to make
node Server.js
work just fine
You can simply use
res.senFile('PATH_TO_FILE');

http server listening in old port

First i installed the node js with webmatrix and ran a sample node js app. the app was assigned a random port. http://localhost:62369/. After that i installed the express module. As said in their doc. i wrote,
var app = express();
app.get('/',function (req, res) {
res.send('hello world!!');
})
app.listen(3000);
Then i restarted the server. The launched browser was still pointing to http://localhost:62369/ instead of port 3000. Moreover http://localhost:3000/ was not working.
I suggest you to run this code so you can see if you have any problem on saving the code with your IDE:
var app = express(),
port = 4555;
app.get('/',function (req, res) {
res.send('hello world!!');
})
console.log("Server is running on " + port);
app.listen(port);
After that, you need to change the port variable only. It's helpful if you comment what you see after running this code on the console.
make sure that you've saved your code in your file (open it with another editor, maybe something's wrong with your editor), close the command line window and open it again. try to run server. I'm sure the problem is not because of node or express. Try to check everything again.
And also run your server with command line:
cd path/folder
node myFile
I don't know what are you using to run server, but if it's something with UI (in comments you mentioned a click) it can cache your code or something like that. So it's safer to run with commend line.

Resources