I am new to Node.js, so I figured I would check it out and do a hello world. I have been having the same issue on all three of my machines, a Win 8, Win 7 and a Mac. Thought at first it was a firewall issue, but I checked and it was off on both Mac and Windows 8 machines (didn't bother checking the win7). When I run Node from the terminal the browser waits for localhost, then eventually times out. I have been at this for two days, can't seem to find any solution via Google. What am I missing.?
Here is my code:
var http = require("http");
console.log("file loaded");
http.createServer(function (request, response) {
request.on("end", function () {
response.writeHead(200, {
'Content-Type': 'text/plain'
});
response.end('Hello HTTP!');
});
}).listen(8080);
You don't need to wait for the HTTP request to end (besides that request.on('end', ..) isn't valid and never fires, and that's why you time out). Just send the response:
var http = require("http");
console.log("file loaded");
http.createServer(function (request, response) {
response.writeHead(200, {'Content-Type': 'text/plain'});
response.end('Hello HTTP!');
}).listen(8080);
Although if you want an easier way to create a HTTP server, the simplest way would be to use frameworks such as Express. Then your code would look like this:
var express = require('express');
var app = express();
app.get('/', function (req, res) {
res.set('Content-Type', 'text/plain');
res.send(200, 'Hello HTTP!');
});
app.listen(8080);
You can also use the connect middleware. Just install it first using npm like so:
npm install -g connect
After this you can make a very simple app like this:
var app = connect()
.use(connect.logger('dev'))
.use(connect.static('public'))
.use(function(req, res){
res.end('hello world\n');
})
.listen(3000);
You can get more information regarding connect here. I tell you to use this, because you get a very simple server, that is easily extensible. However, if you want to make pull blown web sites, then I would sugges using expressjs.
Related
I want to build a MQTT Broker in Typescript with angular. I have tried some examples, but always get the error:
Uncaught TypeError: http.createServer is not a function
Here the simple example i am trying to run at the moment:
var http = require('http');
var port2 = 9000;
http.createServer(function(req, res){
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('Hello there, world\n');
}).listen(port2);
console.log("Listening on port " + port2);
Has anyone an idea where i get this error from, or an other example broker I could try?
Thank you for your help!
Your code is probably being run in the browser while using Node.js APIs.
A Node error would look like this:
While a browser error looks more similar to what you refer to in the question.
The snippet I've run for both of these tests is as follows:
var http = {};
var port2 = 9000;
http.createServer(function(req, res){
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('Hello there, world\n');
}).listen(port2);
console.log("Listening on port " + port2);
Your provided snippet works OK when run on the latest Nodejs docker image with node.
I am new to nodeJS. I am trying to load an index.html page onto my 8080 port and have this:
var http = require('http');
var fs = require('fs');
var PORT = 8080;
function home(req, res) {
if(req.url == '/'){
fs.readFile('index.html', function read (err, data) {
res.writeHead(200, {'Content-type' : 'text/html'});
res.write(data);
res.end();
});
}
};
var server = http.createServer(function (req, res) {
home(req, res);
});
server.listen(PORT);
I have 3 files in the same directory: index.html, style.css, server.js. I start up the server and the page will not load until after I hit cntrl + c. Why is this?
You have written the data to the response, but you have not finished the response. Put res.end(); after your res.write function.
Without this, the browser keeps waiting for more data from the server. When you shut down the server with Ctrl-C, the server closes the connection, and the browser renders what it received.
If you are new to Node, I would recommend looking into something like Express, which handles a lot of important things like routing (what URLs go to which pages) for you and will save you a lot more if statements in the future.
I am trying to send data to the server with the Ajax POST function, and then receive it at the server side with Node.js (and then manipulate it there) but the only problem is that I am unable to find any function at the Node.js side to allow me,accomplish this.I would really like it if you guys could help me out on how to do this as even related threads, I visited on many websites were not very helpful.
Thanks
It will be much easier for you to use some Node-framework like express, to handle all that routes and requests.
You can install it and body-parser module with these commands:
npm install express --save
npm install body-parser --save
Visit express API References to find out more: http://expressjs.com/4x/api.html
var express = require('express');
var bodyParser = require('body-parser');
var app = express();
app.use(bodyParser.json());
// Handle GET request to '/save'
app.get('/save', function(req, res, next){
res.send('Some page with the form.');
});
// Handle POST request to '/save'
app.post('/save', function(req, res, next) {
console.log(req.body);
res.json({'status' : 'ok'});
});
app.listen(3000);
Inside your app.post() route you can get access to any post data using req.body. So your S_POST["name"] will be req.body.name in this case.
here's a simple example:
var http = require('http');
http.createServer(function (request, response) {
switch(request.url){
case '/formhandler':
if(request.method == 'POST'){
request.on('data', function(chunk){
console.log('Received a chunk of data:');
console.log(chunk.tostring());
});
request.on('end', function(){
response.writeHead(200, "OK", {'Content-Type' : 'text/html'});
response.end()
});
}
break;
}
}
Also see this page.
nodejs is built upon javascript, but some methods like alert(), writeln(),... etc are not working in nodejs.
var http = require('http');
http.createServer(function (request, response) {
response.writeHead(200, {'Content-Type': 'text/plain'});
response.end(''+alert('server running')+''); // alert() not working here.
}).listen(8124);
console.log('Server running at http://127.0.0.1:8124/');
How can I use these methods in nodejs programs.
These are the browser functions that your trying to call out. You do not have the access to these global objects like window, document, as these are only browser specific.
The rewritten example would be:
var http = require('http');
http.createServer(function (request, response) {
response.writeHead(200, {'Content-Type': 'text/plain'});
console.log('This will be written in your console');
response.end('server running'); // The response output
}).listen(8124);
console.log('Server running at http://127.0.0.1:8124/');
Those are browser specific methods, of course they don't work in node.
Try console.log( whatYouNeedToLog ) instead.
You can't. They don't make any sense in the context of NodeJS.
If you want to run those functions in the browser, then send the browser an HTML document with embedded JS and not a plain text document.
Ok, I'm new to Node.js so excuse the noob question. Heres my simple code:
var http = require('http');
var fs = require('fs');
// simple node.js server
server = http.createServer(function (request, response){
var get_text = function (errors, contents){
response.write(contents);
response.end('hello world');
}
// get_text is the callback
fs.readFile('log.txt', get_text);
response.write('End of the callback');
response.writeHead(200);
});
server.listen(8000);
console.log('Server running at port 8000');
As it stands, when I run the script in my terminal it will start the server properly but when I go to my localhost:8000 in my browser (chrome) it comes up as "webpage not available".
If I comment out the writeHead command it works fine.
Why?
This is because you're attempting to .writeHead() after .write():
response.write('End of the callback');
response.writeHead(200);
.writeHead() has to be first:
response.writeHead(200);
response.write('End of the callback\n');