I did a little program in nodeJS with cloud9 supposed to launch my html. it worked but without the css. I tried many things but i didn't found the solution.
var http = require("http");
var fs = require("fs");
var events = require('events');
var eventEmitter = new events.EventEmitter();
fs.readFile('homepage.html', function(err, data) {
if (err) return console.log(err);
var server = http.createServer(function (request, response) {
response.writeHead(200, {'Content-Type': 'text/html'});
response.writeHead(200, {'Content-Type': 'text/css'});
response.write(data);
response.end();
}).listen(8081);
});
console.log("Server running.");
my HTML:
<!DOCTYPE html>
<html>
<head>
<title>My project</title>
<meta charset="UTF-8">
<link rel="stylesheet" href="css/style.css"/>
</head>
<body>
<h1>My project</h1>
<p>coming soon</p>
</body>
`
my CSS:
h1{
font-size: 4px;
}
i tried by opening only the .html on my browser and my h1 was 4px.
<link rel="stylesheet" href="css/style.css"/>
You tell the browser to load css/style.css.
The browser asks the server for it.
response.writeHead(200, {'Content-Type': 'text/html'});
The server says "Here is some HTML!"
response.writeHead(200, {'Content-Type': 'text/css'});
Then it says "Here is some CSS!"
Which is very odd. You can send an HTML document or a standalone stylesheet. You can't send both at the same time.
response.write(data);
Then the server sends the contents of homepage.html
So when the browser asks for the style sheet, it gets another copy of the homepage.
You need to pay attention to the request object which tells you what the browser is asking for. In particular pay attention to the method and url properties.
You then need to give it the correct response for that particular URL (which should include the correct content-type for the file type, and could be a 404 error if it isn't a request for something you were expecting).
At the moment you always send the homepage. If the browser asks for /, you send the homepage. If it asks for /css/style.css, you send the homepage. If it asks for /this/does/not/exist, you send the homepage.
Related
tl;dr: Chrome is not sending "If-None-Match" header for HTTPS request but sends it for HTTP request. Firefox always send "If-None-Match", both in HTTPS and HTTP.
I was trying to optimize cookies management for my node server when I came across a weird behavior with Chrome. I will try to describe it and compare it with Firefox.
First, here is the HTTP node server I'm using to test this:
#!/usr/bin/env node
'use strict';
const express = require('express');
const cors = require('cors');
const compression = require('compression');
const pathUtils = require('path');
const fs = require('fs');
const http = require('http');
let app = express();
app.disable('x-powered-by');
app.use(function (req, res, next) {
res.set('Cache-control', 'no-cache');
console.log(req.headers);
next();
});
app.use(express.json({ limit: '50mb' }));
app.use(cors());
app.use(compression({}));
let server = http.createServer(app);
app.get('/api/test', (req, res) => {
res.status(200).send(fs.readFileSync(pathUtils.join(__dirname, 'dummy.txt')));
});
server.listen(1234);
And there the client code :
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
</head>
<body>
<script>
let test = fetch('http://localhost:1234/api/test', { mode: 'no-cors' })
.then((res) => {
return res.text();
})
.then((resText) => console.log(resText));
</script>
</body>
</html>
I use the header "no-cache" to force the client to re-validate the response.
If I've understood correctly how the cache work, I'm expecting client to send the request with the "If-None-Match" header having the previous request's e-tag and the server responding with a 304 code.
Here is the result when I refresh the page in Firefox (so at least one response has already be received). I embedded the server log of the request header.
Here the header "If-None-Match" is sent by the client request, as expected.
Now the same test with Chrome gives :
Well, here Chrome shows a 200 response code, but under the hood, it's really a 304 response that is sent by the server, which is shown by this wireshark capture :
As you can see, Chrome send the "If-None-Match" header with the correct e-tag, hence the 304 response.
So now, let's try this with HTTPS. In the server code, I just replaced require('http'); by require('https') and pass my ssl keys in createServer options (as described here)
So first, Firefox behaviour:
I've included the wireshark capture. And as you can see, everything is right, Firefox has the expected behaviour.
Now let's see the same thing with Chrome :
Here is my problem : as you can see, "If-None-Match" is not sent by Chrome. So as expected, the server returns a 200 response which can be seen in the wireshark capture (I refreshed the page twice, that's why there are 2 exchanges).
Do anyone have an idea on why Chrome has this weird behaviour?
I think it happened because you didn't set in your setting the certificat of your localhost.
Go to the settings and add it :)
chrome settings capture
so I have a very basic file structure going but for whatever reason I cannot get the css to show up in the project when I run it on the localhost. everything else except the css loads here's the structure
enter image description here
I have tried all kinds of path files and have just resorted to straight up copying the entire file path into the relevant parts but still that does not work. I am calling everything from the index.js file.
here's the code for that
const path = require('path');
const express = require('express');
const hbs = require('hbs')
const app = express();
const config = require('./config/request');
const publicDirectoryPath = path.join(__dirname, 'public')
// it was ../public but that did nothing
// also ./public/
// also ../public/
// also /public/
// also public/
const viewsPath = path.join(__dirname, './templates/views')
const partialsPath = path.join(__dirname, './templates/partials')
// error handler
app.use(function(req, res, next) {
if(config.MARKETPLACE_ID === '' || config.SECRET === '') {
res.send('MarketplaceId and secret must be set with your marketplace API credentials');
} else{
next();
}
});
app.set('view engine', 'hbs')
app.set('views', viewsPath)
hbs.registerPartials(partialsPath)
app.use(express.static(publicDirectoryPath))
app.get('', (req, res) => {
res.render('index')
})
app.listen(process.env.PORT || 3000, function(err, req, res) {
if(err) {
res.send('There was no endpoint listening');
} else{
console.log('server started on port: ', (process.env.PORT || 3000));
}
});
css file (it's VERY, VERY complicated so take your time reading through it)
.main-content {
background-color: purple;
}
index.hbs file
<!DOCTYPE html>
<html>
<head>
<title>marketplace</title>
<link rel="stylesheet" src="/literally/the/file/path/I copied/from visual studio code/public/css/styles.css" >
I even put the file into the terminal to get the exact address cause I was convinced I was spelling something wrong
unless all the possible tools used to determine file path on my Mac are wrong then this is the correct file path.
</head>
<body>
<div class="main-content">
so yeah. the index.hbs page should have a purple background. it used to say something about there being an error loading the css file cause of the MIME type or something but I've basically played around with it and got that to go away. now there is no background. no css loaded. and nothing in the console about an error or file not loading. so what gives?
at one point I was trying all of these to load in my css
<link rel="stylesheet" type="text/css" src="actual path copied from the terminal the path is 100% correct>
<link rel="stylesheet type="text/css" href="100% correct file path">
I had the same issue, so solve it you should put in the link src only "/css/styles.css".
<link rel="stylesheet" href="/css/style.css">
I hope it works for you as well.
I am trying to create a very basic static web server that records the IP addresses of each client machine served.
By and large, it is working... but the web site as served has a strange header... b8:
This header doesn't show up in my html at all, and I'm rather confused.
index.html code:
<!DOCTYPE html>
<html>
<head>
<title>Science Treasure Hunt</title>
</head>
<body>
<p>Eventual Home of Science Treasure Hunt Webpage</p>
</body>
</html>
My guess is that it is somewhere on the node.js side of things, but I don't know what could be causing it from that end, either...
index.js code:
let http = require('http');
let requestIp = require('request-ip');
let winston = require('winston');
let static = require('node-static');
http.createServer(onRequest).listen(80);
let logger = winston.createLogger({
level: 'info',
format: winston.format.combine(
winston.format.timestamp(),
winston.format.printf(info => {
return `${info.timestamp} ${info.level}: ${info.message}`;
})
),
transports: [
new winston.transports.Console(),
new winston.transports.File({filename: 'firstlog.log'})
]
});
var file = new(static.Server)('./public');
function onRequest(request, response) {
file.serve(request, response);
var ip = request.headers['x-forwarded-for'] || request.connection.remoteAddress;
logger.log('info', ip);
response.writeHead(200);
}
What might be happening here?
I've been trying to learn how to set up a node.js server for a simple website for the first time and am encountering some strange behavior. When I open my index.html file from my computer it opens up perfectly with all of the CSS working properly. However I then set up a basic node.js server and when accessing the index.html file through my browser it only loads the html but not the CSS.
I'm extremely new to this so haven't been able to try much, also because the code is extremely simple so can't see what's missing (I tried following this tutorial if that helps). I also found another question that seemed similar on here but it didn't have an answer and didn't really help, I did check that all the files are UTF-8.
The HTML:
<html>
<head>
<title>My Page</title>
<link rel="stylesheet" href="styles.css" type="text/css">
</head>
<body>
<h1>A headline</h1>
</body>
</html>
And the node.js server:
const http = require("http");
const fs = require("fs");
const server = http.createServer((req, res) => {
res.writeHead(200, {"Content-Type": "text/html"});
const myReadStream = fs.createReadStream(__dirname + "/index.html", "utf8");
myReadStream.pipe(res);
});
server.listen(3000, "127.0.0.1");
console.log("Listening to port 3000");
When I include the CSS within <style> tags and directly in index.html it does work, but I've tried putting <link rel="stylesheet" href="styles.css" type="text/css"> between <style> tags and that still doesn't (it would also be weird if that's necessary seeing as it displays perfectly when I simply open the html file). I've also tried removing type=text/css but that didn't seem to change anything. Any help would be much appreciated!
You need to serve the style.css as well. You are serving the index.html but in the index.html it is hitting http://127.0.0.1:300/style.css when the request is coming to your app it is STILL serving the index.html file. (You can confirm this in Network pane of developer tools)
const server = http.createServer(function (req, res) {
const url = req.url;
if (url === '/style.css') {
res.writeHead(200, { 'Content-Type': 'text/css' }); // http header
fs.createReadStream(__dirname + "/style.css", "utf8").pipe(res);
} else {
res.writeHead(200, { 'Content-Type': 'text/html' }); // http header
fs.createReadStream(__dirname + "/index.html", "utf8").pipe(res);
}
})
Note: It is very easy to achieve this using express, probably the most popular nodejs package.
I'm practicing pure node js and i've encountred a thing that disturb about http protocole.
I finally served my html page with css after an hour or so of searching and testing my code. Here is my code :
const server = http.createServer((req, res)=>{
if(req.url === "/"){
fs.readFile("index.html", "UTF-8", function(err, data){
res.writeHead(200, {"Content-Type": "text/html"});
res.end(data);
});
}else if(req.url === "/styles.css")){
var cssPath = path.join(__dirname, 'public', req.url);
var fileStream = fs.createReadStream(cssPath, "UTF-8");
res.writeHead(200, {"Content-Type": "text/css"});
fileStream.pipe(res);
};
});
But I didn't understand why it works. Well I've only typed "/" in the browser, I didn't type "/styles.css". And why I don't see "/styles.css" in the URL bar.
I'm sure it's because of how the http protocole is designed but can you help with some explanation of this protocole.
Thank you in advance.
If you had typed /styles.css in the address bar, then you would see the source code the CSS file. For example: this link.
You type /, then the browser asks the server to / and the server responds with an HTML document.
Then the browser renders the HTML document. The HTML document, I assume, includes something like:
<link rel=stylesheet href=/styles.css>
So the browser asks the server for /styles.css and the server responds with a CSS file. The browser then applies that CSS to the HTML document.
It doesn't show /styles.css in the address bar because you are looking at /. The CSS file is just a different resource that is needed to fully render the HTML document that / represents.