node.js http opening static textfiles in browser - javascript

If i have a httpserver in node.js that is serving a website on port 3000.
var httpserver = http.createServer(app).listen(app.get('port'), function(){
console.log('Express server listening on port ' + app.get('port'));
});
app.get('/', function(req, res) {
res.render('index.html');
});
I need to access a txt file located at /public/
If i for example do localhost:3000/other_site.html, if this other_site.html is in /public/ it opens it, but if the file is txt it doesn't open it.
Is there a solution to this without having to install http-request, connect or other npm modules?
Regards,

Can you use express? If yes,
app.use(express.static(__dirname + '/public'))
makes the trick.
If not, try searching the archives :) Using node.js as a simple web server

What error you are getting ?
if you experiencing browser error, try sending response header and set Content Type text/html and retry
Example code
fs.readFile('myfile.txt', function(error, file) {
response.writeHead(200, {'content-type':'text/html'});
response.end();
});

Related

create a web server for local html using node

I'm tring to create a simple web server to run my local html file, and now I can get a server running on localhost using code below
var http = require('http');
var fs = require('fs');
var index = fs.readFileSync('index.html', 'utf8');
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'html'});
res.end(index);
}).listen(3000);
But there is a problem that every time I changed my html file, the web page on localhost is still the old one, I need to restart the server to make the changes visible.
I want to improve that and I tried to use koa or express, like code below
const express = require("express");
const app = express();
app.listen(3000, () => {
console.log("Application started and Listening on port 3000");
});
app.get("/", (req, res) => {
res.sendFile("test.html");
});
And I found that express can serve real-time html files, I don't need to restart serve when files change.
How can I use http moudle to achieve that?
Currently you read the file when the program starts up. Then each time you get a request you serve up the data from the variable.
Move that code inside the callback function that runs when you get a request, then it will be updated each time a request comes in.
http.createServer(function (req, res) {
var index = fs.readFileSync('index.html', 'utf8');
res.writeHead(200, {'Content-Type': 'html'});
res.end(index);
}).listen(3000);
You could avoid reading the file on each request by having the variable outside the function (as in your original code) and watching the file for changes (and updating the variable in response).
That said, using Express and its static module will provide benefits with caching and I'd recommend it over rolling your own.
You can use nodemon.
npm install -g nodemon
nodemon server.js

Deploying nodejs app on a web server

I am new to NodeJS and learning, I want to know how to make an sample app using NodeJS.
I have tried it on localhost and it is working. Now I am trying to host it public to any server, but it is not working.
var http = require('http');
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('Hello World\n');
}).listen(1337, '127.0.0.1');
console.log('Server running at http://127.0.0.1/');
This is code is saved in my local machine as m.js, I run:
$ node m.js
It runs fine and when i open it in browser as https://127.0.0.1:1337
I am getting the output as :
Hello World
I want the same thing to do from a remote server i.e. I have a domain www.example.com and if I open it with https://www.example.com:1337
then it should show on my browser screen like previously :
Hello World
But it is not working.
#Annanta 127.0.0.1:1337 is a local machine ip address. please remove this.
Please find below the sample code. Try to access it with remote server ipaddress. Please note the remote machine must have node and npm installed.
var http = require("http");
http.createServer(function(request, response) {
response.writeHead(200, {"Content-Type": "text/plain"});
response.write("Hello World");
response.end();
}).listen(1337);
console.log('Server running');
Here is a possible work-around using an Apache2-Webserver:
Just edit the Virtual Host in your conf.d (for Ubuntu you´ll find it in /etc/apache/), run a2enmod proxy and restart the Apache.
Here is a possible configuration:
NameVirtualHost *:80
<VirtualHost *:80>
ServerName your-domain.com
ServerAlias www.your-domain.com
ProxyRequests off
ProxyPass / http://127.0.0.1:1337/
ProxyPassReverse / http:/127.0.0.1:1337/
</VirtualHost>
Its actually really simple. Just don't use any IP at all and just define the port.
var http = require('http');
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('Hello World\n');
}).listen(1337);
console.log('Server running!');
Also as Sach stated you can't just upload it to a webserver. You have to have node and npm installed and you have to actually run the code via
$ nodejs application.js

Node JS - Server doesn't react to requests

I set up a Node JS server, and made a request to it, it just loads and loads and eventually says "Server not found". Here is the code for my file:
var http = require('http');
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('Hello World\n');
}).listen(1337, '127.0.0.1');
console.log('Server running at http://127.0.0.1:1337/');
When going to externalIP:1337, the phenomenon described above happens. I am running Ubuntu 14.04, node JS version 0.10.32.
What is going on?
You're specifically listening to 127.0.0.1 which is localhost. If you want to allow connection via the external IP, you should omit the '127.0.0.1' argument in your listen. i.e. change listen(1337, '127.0.0.1') to listen(1337). Otherwise go to localhost:1337 instead.
The problem is that you're only listening for requests on localhost. If you try to access the server from outside the system you won't get there because the server isn't listening on a LAN IP.
Change
.listen(1337, '127.0.0.1');
to
.listen(1337);
That will listen on all available network interfaces on the system. You could specify a LAN IP (just like you did for localhost) if you wanted to listen on a specific network interface.
Sorry.
Apparently tomcat was also using port 80. So by disabling tomcat I got it to work.
Thanks.

Running deployd and angular.js app on the same server

I'm trying to run a deployd API on the same server as my AngularJS app, but deployd seems to be conflicting with the app routing.
My deployd server is listening on port 5000 and looks like this:
var deployd = require('deployd');
var server = deployd({
port: process.env.PORT || 5000,
env: 'production',
db: {
host: 'localhost',
port: 27017,
name: 'deployd',
credentials: {
username: 'myUsername',
password: 'myPassword'
}
}
});
server.listen();
server.on('listening', function() {
console.log("Server is listening");
});
server.on('error', function(err) {
console.error(err);
process.nextTick(function() { // Give the server a chance to return an error
process.exit();
});
});
My node server for the AngularJS app is listening on port 3000 and looks like this:
var express = require('express');
var app = express();
app.use(express.static(__dirname + '/public'));
app.listen(process.env.PORT || 3000);
The app loads fine, although it is not hitting the API as expected when making a call like this:
$http.get('localhost:5000/foo')
or this:
$http.get('http://my.public.ip.address:5000/foo')
And my page routing (in HTML5 mode, with no # in the URL) is getting hijacked by deployd -- so a URL routed by AngularJS for '/foo' is hitting the API and returning "Cannot GET /foo".
This is all happening on a server that is also running Apache, but that is configured to forward requests for my domain to port 3000 using something like this:
NameVirtualHost *:80
<VirtualHost *:80>
ServerAdmin webmaster#localhost
ServerName my.domain.com
ProxyPreserveHost on
ProxyPass / http://localhost:3000/
<Location />
Order allow,deny
Allow from all
</Location>
</VirtualHost>
If I use the # in the URL, like http://my.domain.com/#/foo that will return the page template dictated by the AngularJS router, but it is missing data because the API is not being hit on port 5000.
Any help would be greatly appreciated.
Turns out this was a problem with my Express server.js code and had nothing to do with Deployd. I kept seeing the Cannot GET /foo message and just assuming Deployd was trying to fetch a resource, but in fact Express was not loading index.html (which loads AngularJS and my routing code), because it was just trying to load a static file called foo instead.
Here is my fixed server.js:
var express = require('express');
var app = express();
app.use(express.static(__dirname + '/public'));
app.use(function(req, res) {
res.sendfile(__dirname + '/public/index.html');
});
app.listen(process.env.PORT || 3000);
Now, if the static file foo does not exist, it loads index.html and allows my AngularJS router to take the wheel.
have you checked that from a browser that port 3000 as well as 5000 is reachable?
Because you are using proxy pass it makes me think that those ports aren't open. And because angular is run client side, it will never be able to connect to the api if the 5000 port is closed.

Node.js: cannot get json object on localhost

I have an android app that is going to send a json to my server where I will have a node.js express app. Meanwhile, I want to test it on my localhost.
On my android code I send the json to:
new HttpAsyncTask().execute("http://10.0.2.2:8080/ReceiveJson");
This code is triggered by a button and is working fine.
Then in my app.js file I have the following code:
var express = require('express')
, http = require('http');
var app = express();
app.set('port', process.env.PORT || 8080);
app.get('/ReceiveJson', function(req, res) {
console.log(req.body);
res.send(req.body);
res.json(req.body);
res.send("ok");
});
http.createServer(app).listen(app.get('port'), function(){
console.log('Express server listening on port ' + app.get('port'));
});
In my terminal I run node app.js and I get just the answer "Express server is listening on port 8080". Nothing else.
When I go to my browser and put
http://localhost:8080/ReceiveJson
I get "{}" as an answer.
In my terminal I get the same answer.
What do I have to do to receive the json?
Thanks
That's because you are responding with the req.body:
res.send(req.body);
The code below it never gets called because you have already responded:
res.json(req.body);
res.send("ok");
Because you are using a web browser, there is nothing being sent in the body because it is a get request and there will be nothing in the body for a get request, therefore you get an empty json object, hence {}.
If you change your code to:
app.get('/ReceiveJson', function(req, res) {
res.send("ok");
});
Then when you browse there in your browser you will get the response 'ok'
If you are looking to post or put to your express server then you need to use either app.post or app.put. I noticed that you are trying to send JSON with an Android device for an app you have already written. I would highly recommend using Fiddler or something to test with, just make sure that when you send JSON to your express app you are using the header:
Content-Type: application/json
EDIT:
Your JSON might not be working because you aren't using the body parser. Try inserting this in your code before app.listen
app.configure(function(){
app.use(express.bodyParser());
})

Categories

Resources