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
}
Related
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.
I am having trouble getting my VPS server set up appropriately. I copied all the files recursively from my local server to the remote server, but post & get requests to the server are not functioning appropriately (404 not found error). The routing works perfectly on my localhost server, but unfortunately it doesn't on the remote.
Server Code:
// getting datastores
const datastore = require('nedb');
const customerRecordsdb = new datastore("CustomerRecords.db");
customerRecordsdb.loadDatabase();
// importing express
const port = 3000;
const express = require('express');
const application = express();
const path = require('path')
const newPath = path.join(__dirname + '../../..')
application.listen(port, () => console.log("Listening at " + port));
application.use(express.json( {limit: '1mb'} ));
application.get('/RetrieveCustomerInformation', (request, response) => {
console.log("SUCCESS!");
customerRecordsdb.find({}, (error, data) => {
if (error) {
response.end();
return;
}
response.json(data);
})
})
Client Code:
// loading data
let numberRecords = 0;
async function loadClientRecords() {
const response = await fetch('/RetrieveCustomerInformation');
const data = await response.json();
for (let i = 0; i < data.length; i++) {
numberRecords++;
insertNewRecord(data[i]);
}
}
loadClientRecords()
.then(response => {
// was successful
})
.catch(error => {
//console.log(error);
})
[VPS Page Output]
https://i.stack.imgur.com/ghoIa.png (The server is not outputting anything)
[Local Host Page output]
https://i.stack.imgur.com/I6mqE.png
(The server is outputting "SUCCESS!" on every refresh)
As previously mentioned, I simply copied the directory over to the remote server.
Any help to what the problem could be will be greatly appreciated!
So I'm trying to make a web app, using a node server. I run into a problem where the CSS, Javascript don't work when linking them with a src like or .
The only way I can have css and javascript, is to directly put it inside the script and style parameters, but that doesn't seem that practical
The error that it pulls out shows a url:
127.0.0.1/home.js
why is this happening, and is there a work around?
here is the code
const fetch = require('node-fetch');
const fs = require("fs");
const http = require("http");
const url = require("url");
const server = http.createServer((req, res) => {
// get URL
const pathName = url.parse(req.url, true).pathname;
console.log(pathName);
// create split pathName
const pathSplit = pathName.split("/");
pathSplit.shift();
// HOME PATH
if(pathName === "/home" || pathName === "/"){
// Get HTML data
const data = renderHome();
res.writeHead(200, {"content-type": "text/html"});
fs.readFile(`${__dirname}/templates/template-basic.html`, "utf-8", (err, data) => {
fs.readFile(`${__dirname}/templates/template-battlepass.html`, "utf-8", (err, d) => {
let output = data.replace("{%CONTAINER%}", d);
res.end(output);
});
});
}
// ITEM SHOP PATH
else if(pathName === "/itemShop") {
// Get HTML data
const data = renderItemShop();
res.writeHead(200, {"content-type": "text/html"});
res.end("This is the item shop page");
}
// TOURNAMENTS PATH
else if(pathName === "/tournaments") {
// Get HTML data
const data = renderTournaments();
res.writeHead(200, {"content-type": "text/html"});
res.end("this is the tournaments page");
}
// ITEMS PATH
else if(pathSplit[0] === "items") {
// List all the items for the page
const itemsPages = ["backpacks", "contrails", "emotes", "gliders", "skins", "pickaxes", "wraps"];
let itemConfirm = false;
// If URL has been found, change itemConfirm to true
for(let i = 0; i < itemsPages.length; i++){
if(itemsPages[i] === pathSplit[1]){
// Get HTML data
const data = renderItems(pathSplit[1]);
res.writeHead(200, {"content-type": "text/html"});
res.end(`This is the page for ${pathSplit[1]} in items`);
itemConfirm = true;
}
};
// If itemConfirm is false, no url found
if(itemConfirm === false) {
res.writeHead(404, {"content-type": "text/html"});
res.end(`No URL found for ${pathSplit[1]} in items`);
};
}
// JAVASCRIPT
// NO URL FOUND PATH: 404
else{
res.writeHead(404, {"content-type": "text/html"});
res.end("could not find URL");
}
});
server.listen(1337, "127.0.0.1", () => {
console.log("listening for reqs now");
});
I created a simple server that can serve any type of file using the mime-types library. My basic http server works like this:
const http = require('http');
const fs = require('fs');
const path = require('path');
const mime = require('mime-types'); //Creates the appropriate headerType based on the extension
http.createServer(function (request, response) {
let fileName = path.basename(request.url) || 'index.html' //so that the homepage uses index.html
filePathPart = path.dirname(request.url).slice(1) + "/" + fileName
filePath = "public/" + filePathPart //I store my files in public/js/ or public/css/
console.log(filePath) //just to check if I got the correct files
mimeType = mime.contentType(fileName)
getFile(response, mimeType, filePath)
}).listen(8080);
//I wrote a function to write all the responses the server gives, with this I don't need to expect a specific number of inputs, I can load any number of js/css files or even other html pages.
function getFile(response, mimeType, filePath) {
fs.readFile(filePath, function (err, contents) {
response.writeHead(200, { "Content-Type": mimeType });
response.end(contents);
})
}
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
I am trying my hand at making a simple Node.js server without Express and this where I actually learn a bit more about the down and dirty of actually server files and data on requests based on paths request and basic HTTP stuff.
I have this straightforward server like so:
var http = require('http');
const PORT = 6969;
var allRoutes = require('./routes/all');
var server = http.createServer(allRoutes);
server.listen(PORT, function () {
console.log("Server listening on: http://localhost:%s", PORT);
});
and then I have one "middleware" function like so that handles all requests:
var url = require('url');
var fs = require('fs');
var appRootPath = require('app-root-path');
var path = require('path');
function handleRequest(req, res) {
var requestUrl = url.parse(req.url);
var fsPath;
if (requestUrl.pathname === '/') {
fsPath = path.resolve(appRootPath + '/view/index.html');
}
else {
fsPath = path.resolve(appRootPath + '/view/' + requestUrl.pathname);
}
fs.stat(fsPath, function (err, stat) {
if (err) {
console.log('error occurred...' + err);
return end(req, res);
}
try {
if (stat.isFile()) {
res.writeHead(200);
fs.createReadStream(fsPath).pipe(res);
}
else {
res.writeHead(500);
}
}
finally {
end(req, res);
}
});
}
function end(req, res) {
res.end();
}
module.exports = handleRequest;
the problem I am having is that my function doesn't seem to pipe the response to the browser. The browser shows no evidence of the data come from index.html, which is a barebones .html HTML5 file.
I stole the example, and am surprised it's not really working. Anyone have an idea? I know for sure that the fs.stat function is not experiencing an error and then it is streaming the index.html file, it just doesn't seem to be streaming to the right place...
For starters:
if (requestUrl.pathname = '/')
should be:
if (requestUrl.pathname === '/')
Your code was assigning, not comparing.
In addition, the .pipe() is asynchronous, but you are calling res.end() BEFORE it gets to do it's job in your finally{} block which closes the response stream and stops your pipe from doing anything. By default .pipe() will close the write stream by itself, so you don't need the res.end() at all when using .pipe().
You can change the code to this:
var url = require('url');
var fs = require('fs');
var appRootPath = require('app-root-path');
var path = require('path');
function handleRequest(req, res) {
var requestUrl = url.parse(req.url);
var fsPath;
if (requestUrl.pathname === '/') {
fsPath = path.resolve(appRootPath + '/view/index.html');
}
else {
fsPath = path.resolve(appRootPath + '/view/' + requestUrl.pathname);
}
fs.stat(fsPath, function (err, stat) {
if (err) {
console.log('error occurred...' + err);
return end(req, res);
}
try {
if (stat.isFile()) {
res.writeHead(200);
fs.createReadStream(fsPath).pipe(res);
}
else {
res.writeHead(500);
end(req.res);
}
}
catch(e) {
end(req, res);
}
});
}
function end(req, res) {
res.end();
}
module.exports = handleRequest;