Node js- not able to define chunk constant - javascript

The function activated by the listener on http.incomingMessage is not working properly, it is supposed to define the constant chunk white the submited input but for some reason it remain UNDEFINED.
I dont get any error message but the page wont stop loading after accessing the page.
const http = require('http');
const fs = require('fs');
const server = http.createServer((req, res) => {
const url = req.url;
const method = req.method;
if (url === '/') {
res.write('<html>');
res.write('<head><title>Enter Message</title></head>');
res.write('<body>');
res.write('<form action="/message" method="POST">');
res.write('<input type="text">');
res.write('<input type="submit">');
res.write('</form>');
res.write('</body>');
res.write('</html>');
return res.end();
}
if (url === '/message') {
const body = [];
req.on('data', chunk => {
body.push(chunk);
});
return req.on('end', () => {
const parsedBody = Buffer.concat(body).toString();
const message = parsedBody.split('=')[1];
console.log(parsedBody);
fs.writeFileSync('message.txt', message, err => {
res.statusCode = 302;
res.setHeader('Location', '/');
return res.end();
});
});
}
res.setHeader('Content-Type', 'text/html')
res.write('<html>');
res.write('<head><title>Enter Message</title></head>');
res.write('<body>');
res.write('<p>My page</p>');
res.write('</body>');
res.write('</html>');
res.end();
});
server.listen(8080);

You are not calling the function properly, change your res.end; to res.end();.
In order to finish sending a request you have to invoke the res.end() function

Related

html page loading but CSS is not in node js app

I've made a weather app using pure node js , but ultimately when i load the website, it only loads the HTML site and note the CSS.
Here is my index.js
const fs = require("fs");
const http = require("http");
var requests = require("requests");
const homeFile = fs.readFileSync('home.html', 'utf-8');
const replaceVal = (tempVal, orgVal) => {
let temperature = tempVal.replace("{%tempVal%}", orgVal.main.temp);
temperature = temperature.replace("{%minTemp%}", orgVal.main.temp_min);
temperature = temperature.replace("{%maxTemp%}", orgVal.main.temp_max);
temperature = temperature.replace("{%country%}", orgVal.sys.country);
return temperature;
}
const server = http.createServer((req, res) => {
if (req.url == '/') {
requests('https://api.openweathermap.org/data/2.5/weather?q=Pune&appid=0bfd89f4982a2d416a4ac5d299d03f9e&units=metric')
.on('data', function (chunk) {
const objData = JSON.parse(chunk);
const arr = [objData];
const realTimeData = arr.map(val => {
return replaceVal(homeFile, val);
}).join("");
res.write(realTimeData);
})
.on('end', function (err) {
if (err) return console.log('connection closed due to errors', err);
res.end();
});
}
});
server.listen(8000, "127.0.0.1");
Can anyone help in solving this issue.
It looks like you are only sending homeFile to your response for path "/". If you want to output your css as well you will need another path matching for any css files. That way when your html file asks the server for the css file it can request it.
if(req.url === "/"){
//send html here
}else if(req.url.match("\.css$")){
//send css here
}

node.js, page not redirecting - statusCode, setHeader

It should redirect back to the "/" root url, but somehow it's not working properly.
it gives the 302 confirmation, but it wont get there
const fs = require("fs");
function requestHandler(req, res) {
const url = req.url;
const method = req.method;
if (url === "/") {
res.write("<html>");
res.write("<head><title> Minha primeira página! </title></head>");
res.write(
"<body><form action='/message' method='POST'><input type='text' name ='message'><button type='submit'>Enviar</button></form></body>"
);
res.write("</html>");
return res.end();
}
//console.log(req.url, req.method, req.headers);
if (url === "/message" && method === "POST") {
const body = [];
req.on("data", (chunk) => {
console.log(chunk);
body.push(chunk);
});
req.on("end", () => {
const parsedBody = Buffer.concat(body).toString();
const message = parsedBody.split("=")[1];
fs.writeFile("message.txt", message, (err) => {});
});
res.statusCode = 302;
res.setHeader = ("Location", "/");
return res.end();
}
}
Redirect to "/" after solving /message
You can use redirect to go to the home page like
res.redirect('/');

Routing for static site causes endless loading in browser when readFile() is in an if statement

I am trying to create routing for a static site however placing readFile() in an if statement causes infinite loading in my browser and content doesn't load.
I'm trying to do this without the use of Express or any similar framework.
Here is my code:
var http = require("http");
var fs = require("fs");
var url = require("url");
var path = require("path");
var server = http.createServer((req, res) => {
let parsedURL = url.parse(req.url, true);
let fPath = parsedURL.path;
if (fPath === "/") {
fPath = "/index.html";
}
file = path.join(__dirname, "/public" + fPath);
if (fPath === "/index.html") {
fs.readFile(file, (err, data) => {
if (err) {
console.error(err);
res.end("An error has occured.");
} else {
res.end(data);
}
});
} else if (fPath === "/information.html") {
fs.readFile(file, (err, data) => {
if (err) {
console.error(err);
res.end("An error has occured.");
} else {
res.end(data);
}
});
}
});
server.listen(8000);
If if (fPath === "/index.html") { matches and fs.readFile has an error, then you don't send a response.
The same is true for "/information.html".
And if fPath isn't either of those then you get to the end and you don't send a response.
The endless loading is caused by the browser waiting for a response you never send.
You need to make sure that every path through your if statements calls res.end or another function that sends a response to the browser.

node server (without Express) does not render image and it keeps loading at localhost

I created a server without express and I'm trying to server a simple static webpage on localhost
here is my code :
const fs = require('fs')
const url = require('url');
const hostname = 'localhost'
const port = 3000;
const path = require ('path');
const http = require ('http')
const server = http.createServer((req, res) => {
if (req.url.match (/.css$/)) {
let cssPath = path.join (__dirname, req.url)
let cssReadStream = fs.createReadStream (cssPath, 'UTF-8')
res.statusCode = 200;
res.setHeader ("Content-Type", "text/css");
cssReadStream.pipe (res)
}
if (req.url === "/") {
fs.readFile("./index.html", 'UTF-8', (err, data) => {
res.statusCode = 200;
res.setHeader("Content-Type", "text/html");
res.end(data);
})
}
if (req.url.match (/.jpg$/)) {
let jpgPath = path.join (req.url)
console.log (jpgPath)
let jpgReadStream = fs.createReadStream (jpgPath, 'UTF-8')
res.statusCode = 200;
res.setHeader ('Content-Type', 'image/jpg')
jpgReadStream.pipe (res)
}
})
server.listen (port, hostname, () => {
console.log ('server start')
})
first of all, it can display the HTML and CSS, however, localhost just keeps on loading after HTML and CSS displayed. Second of All, the image cannot be display (a instagram icon name icon.jpg).
the end result should look something like this:
I guess it has something to do with the favicon thing, but how do i fix it?
you need to use response.send() function which will be used to send the response back
const server = http.createServer((req, res) => {
if (req.url.match (/.css$/)) {
let cssPath = path.join (__dirname, req.url)
let cssReadStream = fs.createReadStream (cssPath, 'UTF-8')
res.statusCode = 200;
res.setHeader ("Content-Type", "text/css");
cssReadStream.pipe (res)
res.send("your data")
}
if (req.url === "/") {
fs.readFile("./index.html", 'UTF-8', (err, data) => {
res.statusCode = 200;
res.setHeader("Content-Type", "text/html");
res.end(data);
res.send("your data")
})
}
if (req.url.match (/.jpg$/)) {
let jpgPath = path.join (req.url)
console.log (jpgPath)
let jpgReadStream = fs.createReadStream (jpgPath, 'UTF-8')
res.statusCode = 200;
res.setHeader ('Content-Type', 'image/jpg')
jpgReadStream.pipe (res)
res.send("your data")
}
})

Headers, Node.js , Can\'t set headers after they are sent

I'm new in node.js and I'm implementing a Static file server.
what i'm trying to do is just get the file name from the url and display it. running the code id get this error:
_http_outgoing.js:489
throw new Error('Can\'t set headers after they are sent.');
Error: Can't set headers after they are sent.
this is my code
#!/usr/bin/env node
/*
* Basic node.js HTTP server
*/
const http = require('http');
const url = require('url');
const fs = require('fs');
const routes = Object.create(null);
function file(rew, res, serched) {
let fileSerched = serched[serched.length - 1]
fileSerched = __dirname + "/NodeStaticFiles/" + fileSerched;
fs.readFile(fileSerched, function(err, data) {
if (err) {
res.statusCode = 500;
res.end(`Error getting the file: ${err}.`);
} else {
res.setHeader('Content-type', 'text/plain');
res.writeHead(200)
res.end(data);
}
})
}
routes['file'] = file;
function onRequest(req, res) {
const pathname = url.parse(req.url).pathname
const uri = pathname.split('/', 3)[1]
let splittedPathname = pathname.split('/')
splittedPathname.shift()
splittedPathname.shift()
if (typeof routes[uri] === 'function') {
routes[uri](req, res, splittedPathname);
} else {
res.statusCode = 404;
res.end(`File not found!`);
}
res.end()
}
http.createServer(onRequest).listen(3000);
console.log('Server started at localhost:3000')
You need to make sure your code won't call something like res.end() more than once. For example:
function onRequest(req, res) {
const pathname = url.parse(req.url).pathname
const uri = pathname.split('/', 3)[1]
let splittedPathname = pathname.split('/')
splittedPathname.shift()
splittedPathname.shift()
if (typeof routes[uri] === 'function') {
routes[uri](req, res, splittedPathname);
} else {
// THIS WILL CALL res.end() and continue on
res.statusCode = 404;
res.end(`File not found!`);
}
// THIS WILL CALL res.end() AGAIN!!
res.end()
}
try adding a return after you call res.end() in an if/else

Categories

Resources