Iframe "(Site Name) Refused to Connect." Error - html

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');
}
}

Related

Trying to load my html file using nodejs to create login page

I am trying to use node.js to run a html file. I already have a login.html and styles.css for for the login page but now I don't know how to use the node js file to run my login.html page. I follow this youtube tutorial to make the a login authentication. It seems to have everything needed but now I dont know how to use it in my login.html file.
I need help modifying this so that I can run my login.html file.
index.js file
const express = require('express');
const app = express();
const mongoose = require('mongoose');
const dotenv = require('dotenv');
const postRoute = require('./routes/posts');
//Import Routes
const authRoute = require('./routes/auth');
dotenv.config();
//Connect to DB
mongoose.connect(
process.env.DB_CONNECTION,
{ useNewUrlParser: true, useUnifiedTopology: true },
() => console.log('Connected to DB')
);
//Middleware
app.use(express.json());
//Routes Middlewares
app.use('/api/user', authRoute);
app.use('/api/posts', postRoute);
// start listening
app.listen(3000, () => console.log('Server up and running port:3000'));
I am new to node.js and am completely lost on how to solve this problem.
you can solve it in two ways, first you can install view engine like ejs and use res.render (if you want more about it i can explain)
Second you can response with the HTML file like this: (works only with express and you have express)
app.get('/yourRotue', function(req, res, next){
res.sendFile(__dirname + '/yourPath/htmlFile.html');
});
How to use EJS (basic):
First please install EJS with npm install ejs install body parser npm install body-parser
now you need to create two folders on the root folder, public and views.
inside views you can create a folder auth and put your EJS files there.
then on your app.js (or index.js, the main file) add view engine middleware:
(*notice that you dont need to require ejs, also notice you dont need to install path its built in with node)
//import body parser on top (to parse json/urlencoded/text..
const bodyParser = require('body-parser');
//import path so you can use it for the public folder
const path = require('path');
//this line makes public folder public so you can store js/css/image...
app.use(express.static(path.join(__dirname, 'public')));
//use the body parser as middleware
app.use(bodyParser.json({ limit: '200mb' }));
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.text({ limit: '200mb' }));
//this line tells node js to use ejs
app.set('view engine', 'ejs');
//this line make sure that the views folder is the folder with the ejs files
app.set('views', 'views');
//now your route will look like this:
app.get(/routeName, (req,res,next) => {
let example
//you return response with render, to render the file you want.
// you dont write the views folder name, only the file name without .ejs
// elso you can run functions here and later send the response to the front end
function(){
example = 1 + 1 * 5
}
// *very often the function above is to find something in the db
return res.render('auth/ejsFileName', {
pageTitle: 'some page title for the example',
exampleKey: example
})
})
I can suggest you to use mvc (models, views, controllers) structor, if you want to know more about it you can open new question or to search about it.
EJS:
put your css and js in public folder, you can create js folder and css folder inside the public folder and then put the css in js in their folder.
*notice you dont need to write ./public in the route.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="/css/someCssFile.css">
<!-- here is the title that comes from the back end -->
<title><%= pageTitle %></title>
</head>
<main>
<h1>Here you can see the example with the function<%= exampleKey %></h1>
</main>
<script src="/js/someJsFile.js"></script>
</body>
</html>
the file look like html but it has .ejs
there is many things you can do with ejs like to loop through values.. i would suggest to learn a bit more.
this is the basic it should work.
For the post request i need to know if you are posting a form as urlEncoded or json. so i can show you how it should look like.
You can try to use some template engines like Handlebars. https://youtu.be/1srD3Mdvf50 You can try to follow this tutorial in order to load some html from the server side. Then you can use different selectors in order to interact with DOM elementa

CSS won't load in hbs file for some reason

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.

Strange header ("b8") in node-static web server page

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?

Server or HTML isn't displaying CSS (but works when opening HTML file)

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.

Nodejs load my HTML without the CSS

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.