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?
Related
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.
EN : The content of the iframe element I use in my project is "(site name) refused to connect." I get the error how can I fix this error?
TR : Projemde kullandığım iframe öğesinin içeriği "(site adı) bağlanmayı reddetti." Hatası alıyorum, bu hatayı nasıl düzeltebilirim?
<iframe src="https://www.google.com/" frameborder="0"></iframe>
https://jsfiddle.net/fatihege/2he1nuyf/
I've been trying to get around this for months, and finally found a very easy solution that I haven't seen anyone mention. If you're trying to use an iframe to include a website that won't let you, create your own php file, I named mine iframe.php. In that file, put this:
<!DOCTYPE html><html><?php echo file_get_contents($_REQUEST['url']); ?></html>
Then, in your iframe, use the src url 'iframe.php?url=http://www.website.com'.
It's not your code as sites can block themselves from being framed.
This is because of a certain header set (X-Frame-Options) as per the mozilla docs: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/X-Frame-Options
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
</head>
<body>
<iframe src="https://www.google.com/" frameborder="0"></iframe>
</body>
</html>
But with another domain (example.com):
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
</head>
<body>
<iframe src="https://www.example.com/" frameborder="0"></iframe>
</body>
</html>
In cases where you aren't allowed to view the site, you can rely on the server side for this. Basically the concept is the server will fetch the file and append it at the given location.
As pointed out by #Dale's answer, this can be done with php.
For those using other server side languages, basically the same principle is applied.
An implementation of this in node will be something like:
const express = require('express');
const fs = require('fs');
const { execSync } = require('child_process');
const app = new express();
const PORT = 3000;
const fetchWebsite = (url) => {
execSync(`wget -q -O - ${url} > site.html`,
(error, stdout, stderr) => {
if (error !== null) {
return false;
}
});
}
app.get('/', async (req, res) => {
fs.writeFileSync('site.html', '', () => console.log('Created site.html'));
fs.createReadStream('site.html').pipe(res);
fetchWebsite('https://www.stackoverflow.com');
});
app.listen(PORT, () => {console.log("Listening at port: ", PORT)} )
Of course this assumes you're using a standard Linux server and you've installed the express module.
this might help a little if you need to write the above #scoochy's expressjs code in nestjs
import { Controller, Get, Response } from '#nestjs/common';
import { execSync } from 'child_process';
import { createReadStream, writeFileSync } from 'fs';
#Controller('iframe')
export class IFrameController {
fetchWebsite = (url) => {
execSync(`wget -q -O - ${url} > site.html`);
};
#Get()
getFile(#Response() res) {
writeFileSync('site.html', '');
createReadStream('site.html').pipe(res);
this.fetchWebsite('https://www.stackoverflow.com');
}
}
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 need to send a warning message from express to the browser.
So, I need help to do it. Currently I am working with a MEAN app.
Here, I have to communicate between Express and HTML.
I will give you an example using express and .ejs as a view engine. It gives more flexibity than plain .html but is still simple (and looks nearly identical).
This way you can setup your routing (the way you redirect users to different sites based on address/path) and at the same time pass data to your views.
router.js
var express = require('express');
var router = express.Router();
router.get('/', function (req, res, next) {
res.render('someView', {msg: 'Express'});
});
Above will pass a variable called msg with value Express and render yourView (basically some of your pages).
yourView.ejs
<!DOCTYPE html>
<html>
<head>
<title><%= msg %></title> // here is how you can use variable passed from back-end in .ejs templates
</head>
<body>
<h1>Hello there</h1>
</body>
</html>
Of course you can pass arrays, json, obj etc. to your view.
router2.js
var arr = ['a', 'b', 'c'];
var obj = {a: 1, b: 1, c: 2, d: 3, e: 5};
var objJSON = JSON.stringify(obj);
res.render('demo', {arr: arr, objJSON: objJSON}); // key: value, so you will refer by key in your view
You could also use this values in view's JS scripts.
For example like this
// html/ejs markup here
<body>
// bla bla...
<script>
var tmp = <%= msg %>
alert(tmp);
/* obviously you need some kind of logic when you want
alert/popup or whatever to happen. At least some simple IF statement.
*/
</script>
</body>
</html>
However more popular way to display messages to end-users in express is using flash messages. Check out this link to Connect-Flash middleware. Simple usage is exapl
See the docs of express and read about response. Example:
app.get('/user/:id', function(req, res){
res.send('user ' + req.params.id); // Send to view (html,jade, ejs) somethink message
});
The res object represents the HTTP response that an Express app sends
when it gets an HTTP request.
There are more responses methods, as res.sendFile, res.render, res.redirect, etc.
I am trying to make this web site that resides in Google Drive control a LED(on/off) via esp8266 and arduino. Partially i've succeded in doing what i want by sending to the IP of the module that communicates with the arduino a GET request witch parses it and acts accordingly. ie GET /?LED1=on HTTP/1.1
Problem is that whenever i press a button in the web site it sends the GET request and then it waits for a response from the other end (arduino),and the browser keeps loading until eather I close the connection from the arduino or I reply something like HTTP/1.1 200 OK and then close the conection.
In the first case browser shows the message that was unable to load the page and in second case it simply shows a blank page.
<DOCTYPE html>
<html>
<head>
<title>LED Control</title>
</head>
<body>
<button>LED 1 On</button>
</body>
</html>
I just want to send that LED1=on string somehow without causing the page attempt to load anything back.
A reusable solution
Modify your HTML to be something like this:
<button class="get" data-url="http://78.87.xxx.xx:333/?LED1=on">LED 1 On</button>
Now add this JavaScript:
window.onload = function () {
Array.prototype.forEach.call(document.querySelectorAll('.get'), function(el) {
el.onclick = function () {
// Use this trick to perform CORS requests too
var req = new Image();
req.src = this.dataset.url;
// The following 7 lines are completely optional
req.onload = function () {
// Was successful
};
req.onerror = function (error) {
// Encountered an error
alert('An error occurred while performing the request. + ' error);
};
};
});
};
Now any element with the class "get" when clicked, will send a request to the URL. This won't change the page either. If