Node.js webserver CHUNKED encoding issue - javascript

I'm trying to build a node.js webserver that listens on port 9000 and reads a js file when requested then sends the output on the response. This is what I have so far:
var http = require('http'),
fs = require('fs'),
path = require('path');
http.createServer(function(request, response){
response.writeHead(200, {'Content-Type': 'text/javascript'});
switch (request.url){
case '/main.js' :
fs.createReadStream(path.normalize('C:\\dev\\projects\\main.js')).pipe(response);
response.end()
break;
case '/page.js' :
fs.createReadStream(path.normalize('C:\\dev\\projects\\src\\page.js')).pipe(response);
response.end()
break;
case '/page2.js' :
fs.createReadStream(path.normalize('C:\\dev\\projects\\src\\page2.js')).pipe(response);
response.end()
break;
default :
response.writeHead(404);
response.write('Not Supported');
response.end();
break;
}
}).listen(9000);
console.log('listening on port 9000........')
I call the main.js file from the HTML page like so:
<script type="text/javascript" src="http://localhost:9000/main.js"></script>
When running the page, the first case in the code should run but all I get is this error in the browser console.
GET http://localhost:9000/main.js net::ERR_INVALID_CHUNKED_ENCODING
I tried playing around with the headers in the response with no success. Any ideas?

Related

Node JS/localhost server is not showing the image

I created localhost/server on node js, and my pictures/img tag doesn't work
<div class="text-center">
<img alt = "Bulb" src="pic_bulboff.gif" class="rounded" alt="bulboff">
</div>
but the problem is that they show up when I open them in a regular browser without the server
const http = require('http')
const fs = require('fs')
const port = 3000
const server = http.createServer(function(req, res){
res.writeHead(200, { 'Content-Type': 'text/html'})
fs.readFile('index.html', function(error, data) {
if(error) {
res.writeHead(404)
res.write('Error: File not Found')
} else {
res.write(data)
}
res.end();
})
})
above is the node server.
is there a problem that I can't really see?
Thanks!!!
By default a nodejs http server does not serve ANY files at all. You've created an http server that serves index.html for ALL incoming requests. So, a browser makes a request from your web server and you send it the HTML content from index.html.
Then, the browser parses that HTML and sees an <img> tag with a src attribute of "pic_bulboff.gif" so the browser then sends a request to your web server asking it for the content for /pick_bulboff.gif. But, you web server just responds to that request by sending index.html. That obviously doesn't work. You need your web server to know the difference between different path requests so it will server index.html when the browser is requesting /, but will serve that image when the browser is requesting /pick_bulboff.gif.
While most people will use a simple web framework that has the serving of static files as a built-in feature (like the Express framework), you can do it manually if you want:
const http = require('http');
const fs = require('fs');
const port = 3000;
function sendFile(fname, contentType) {
res.writeHead(200, { 'Content-Type': contentType});
fs.readFile(fname, function(error, data) {
if(error) {
res.writeHead(404);
res.write('Error: File not Found');
} else {
res.write(data);
}
res.end();
}
}
const server = http.createServer(function(req, res){
if (req.url === "/") {
sendFile('index.html', 'text/html');
} else if (req.url === '/pick_bulboff.gif') {
sendFile('pick_bulboff.gif', 'image/gif');
} else {
res.writeHead(404);
res.end('Error: Unsupported path');
}
});
server.listen(port);
In a more typical implementation, you would put all static files in one directory hierarchy that was separate from your code and you would use functionality similar to express.static() in the Express framework to serve any file in that static files directory that matches an incoming request so you don't have to create a custom route for every single static file you're using in your project.

Syntax error with NodeJS and HTTP

var http = require("http");
http.createServer(function(request,response) {
response.writeHead(200, {"Content-Type": "text/plain"});
response.writeHead(" This is just a start.. Remember what u thought of it.");
reponse.end();
}).listen(8888);
This is my JS code in a file named server.js which I wanted to execute through Node.js, but it's giving an error:
SyntaxError: Unexpected identifier
The path of the file, server.js is in D Drive, same as where I installed Node.js. What should I do ?
Use this code:
var http = require("http");
http.createServer(function(request,response) {
response.writeHead(200, {"Content-Type": "text/plain"});
response.write(" This is just a start.. Remember what u thought of it.");
response.end();
}).listen(8888);
Save it in a file named "server.js" and run it with:
node server.js
I don't know if it's a typo in your question but you use reponse instead of response:
var http = require("http");
http.createServer(function(request,response) {
response.writeHead(200, {"Content-Type": "text/plain"});
response.writeHead(" This is just a start.. Remember what u thought of it.");
reponse.end(); // <------
}).listen(8888);

Running Node.js Server using User Level Root

Basic question but not sure where to turn to start figuring this out.
I've setup a very simple node server on port 3000 that just responds with an index.html file. When I call http://localhost:3000 in the browser, I get the proper page served up with dependencies. I don't want to authenticate every time though so I'd like to run it from the user-level.
I tried typing http://localhost~myusername:3000 in the browser but I keep getting:
The requested URL /~myusername:3000 was not found on this server.
(I have setup user-level root to be accessed through ~/Sites and have gotten access to files through here, even php, it's just when I start using a node server this problem occurs.)
How can I get node.js to respond to user-level requests? And it serve up the proper index.html from the relative path of the user-level root instead of /library/WebServer/Documents?
Update
Code of server.js:
var http = require('http');
var fs = require('fs');
function send404(response) {
response.writeHead(404, { 'Content-Type': 'text/plain' });
response.write('Error 404: Resource not found.');
response.end();
}
var server = http.createServer(function (req, res) {
if (req.method == 'GET' && req.url == '/') {
res.writeHead(200, { 'content-type': 'text/html' });
fs.createReadStream('./index.html').pipe(res);
}
else {
send404(res);
}
}).listen(3000);
console.log('server running on port 3000');

Linking css files to node.js server

So I have craeted a node.js server with two routes. I use the fs to get the html files from the views folder and then append them to the page. In those html files I have a normal link to the css file, which does not seem to work. Here is my node.js app:
var port = 1357;
var http = require('http'),
path = require('path'),
mime = require('mime'),
fs = require('fs');
var app = http.createServer( function(req, res) {
if (req.url === '/home') {
fs.readFile('views/index.html', function(err, page) {
res.writeHead(200, {'Content-Type': 'text/html'});
res.write(page);
res.end();
});
}
else if (req.url === '/about') {
fs.readFile('views/about.html', function(err, page) {
res.writeHead(200, {'Content-Type': 'text/html'});
res.write(page);
res.end();
});
}
else {
res.writeHead(301,
{Location: '/home'}
);
res.end();
}
});
app.listen(port);
console.log('Server running on port: ' + port)
In the html files I have:
<link rel="stylesheet" type="text/css" href="./styles/styles.css">
It does not work. In chrome's console I get "Resource interpreted as Stylesheet but transferred with MIME type text/html. "
You defined 2 routes: /home and /about. You also defined that anything apart from these two routes should default to an HTTP redirect to the /home route, and this is what causes the problem.
When the browser encounters the link to the css file, it requests the following URL: /styles/styles.css. the server receives this URL and since it doesn't match the two defined routes it will go into the else statement which will send a redirect to /home, so your browser, asking for a css file, will only receive the html page located in /home.
To fix this, you might need to add a new rule for your css file:
else if (req.url === '/styles/styles.css') {
fs.readFile('styles/styles.css', function(err, page) {
res.writeHead(200, {'Content-Type': 'text/css'});
res.write(page);
res.end();
});
}
Of course, if you have more css files you need to manage a specific folder instead of files. I suppose you're doing this to learn Node, because if you don't you might want to use express which is a Node ready to use web server that will save you lot of time.
When the client (the browser) asks the server for /styles/styles.css the server responds with 301 Moved Permanently and Location: '/home'.
The browser then asks for /home and gets an HTML document, which is not a stylesheet.
You have to give the browser the stylesheet when it asks for it.
static assets (as in your stylesheets) wont be served automatically. So what happens is that it falls through and lands at the 301 redirect to /home, where you serve text/html.
If you want to serve css that way, add a rule req.url==="/styles/styles.css"
Generally, I would recommend using a routing lib like express or koa. Or as minimum, connect. They make it easy to hook in features called middleware and enable you to make everything in a directory (like /public) serve static content with one rule.

Node.js exports module not working

I am very beginner to node.js, I found a tutorial to learn. while I learn I used this code to run my server it works fine:
code :
var http = require ("http");
http.createServer (function (request, response) {
response.writeHead(200, {"Content-Type" : "text/plain"});
response.write("Hellow world! I written my first server side code!"); //browser responding
response.end();
} ).listen(8888);
But while I tried to export the server like this,
var http = require("http");
function start() {
function onRequest(request, response) {
console.log("Request received.");
response.writeHead(200, {"Content-Type": "text/plain"});
response.write("Hello World");
response.end();
}
http.createServer(onRequest).listen(8888);
console.log("Server has started.");
}
exports.start = start; // the export module not work?
and i am getting an error in browser like this:
Failed to load resource: Could not connect to the server.
I am not able to start my server, and export the module any one suggest me the fix for this please?

Categories