How to display static html page with image on Heroku - html

I'm trying to display an html page on Heroku that has an image tag. The image exists but I cannot figure out what path to use so that it can be found. I keep getting 404 errors with every absolute path I try, and I can't use a relative path, because it appends it to the place the html page was loaded from (which happens to be /api/errorcodes/x where x is a number that is used to find the original html page) I.E.
app.get('/api/errorcode/:errorcode', function(request, response) {
var errorcode = request.params.errorcode;
var doc = 'Error' + errorcode + '.html';
console.log('__dirname = ', __dirname);
response.sendFile(__dirname + '/views/pages/' + doc);
});
So the directory structure is as follows:
views/pages/Error1.html
views/pages/Error1.fld/img001.png
And Error1.html has <img src="/views/pages/Error1.fld/img001.png"> and returns 404 (The page Error1.html loads, but the image gets a 404 in the heroku logs).
I have also tried "/app/views/pages/Error1.fld/img001.png" as well as moving the image to /public and trying the same combinations from there. How do I tell the img tag where to find the image?!

Ok I finally figured this out. In case anyone else comes across this here is the answer:
Before declaring any routes, add the static middleware:
app.use(express.static(__dirname + '/public'));
"The static middleware has the same effect as creating a route for each static file you want to deliver that renders a file and returns it to the client" - excerpt from O'Reilly's Web Development With Node & Express book.
Then in the html file you can use <img src="/img/logo.png"> if your image file is at public/img/logo.png.

Related

External CSS are not getting Applied on exported PDF Using jspdf's .html() method

My Goal is to Export All Pages in the PDF, For Exporting PDF I'm using jsPDF.HTML() method, Here is my code
const exportToPdf = () => {
const doc = new jsPDF("p", "pt", "a4");
doc.html(page1 + page2 + page3 + page4 + page5, {
callback: function (pdf) {
pdf.save("multipage.pdf");
window.open(pdf.output("bloburl"));
},
dompurify: dompurify,
margin: 50,
});
Here page1, page2, page3 are HTML strings For that specific page. I'm rendering those pages using Tabs! styling for All those pages are given by external CSS file.
while exporting from the localhost it is working fine & CSS changes from the external file also applies, but when we export it from the Hosted Site only CSS given with the inline styling are applying not from the external file
This is the log I'm getting in console:
Failed to load resource: the server responded with a status of 403 (Forbidden)
whether it is possible that Azure is creating the issue ?
I don't know what's the issue behind that, Your suggestion will be very helpful, Thanks!!

Display image that returns HTTP 503 in Firefox

I have a status badge image that returns the HTTP code 503 when the respective service is offline (but the webserver is still there serving calls). Now opening the image URL directly will display the image properly, regardless of the underlying 503 error code. But using it inside an <img> tag shows the broken image icon. How can I prevent that while still allowing the image itself to return a 503? (External services depend on that)
Here are some screenshots to illustrate what's going on:
The badge on the page:
The status message in the developer console:
The badge itself:
Note: This happens on Firefox. Not Chrome
Edit: Here are a few requested pieces information:
Firefox 78.0.2 (64-Bit)
It's served from the same domain. But the domain is essentially just proxying serveral underlying webservices. And this badge is originating from a different service but all on the same domain.
It's a SVG image if that makes any difference.
Since XMLHttpRequest can retrieve the output of any request, no matter the response code, it is possible to request for the image with XMLHttpRequest, and then convert the blob response type to a base64 format image, which can be loaded in the browser.
The CORS proxy I used in the sample code may not be necessary in the majority of cases, but could be useful in the case where the image you are trying to display has weird response headers that prevent access to the image from another domain.
Here is the sample code. It should work no matter the response code, CORS, etc.
var xhr = new XMLHttpRequest();
xhr.onload = function () {
var reader = new FileReader();
reader.onloadend = function () {
// here, reader.result contains the base64-formatted string you can use to set the src attribute with
document.getElementsByTagName('img')[0].src = reader.result; // sets the first <img> tag to display the image, change to the element you want to use
};
reader.readAsDataURL(xhr.response);
};
xhr.open('GET', "https://cors-anywhere.herokuapp.com/i.stack.imgur.com/8wB1j.png"); // don't include the HTTP/HTTPS protocol in the url
xhr.responseType = 'blob';
xhr.setRequestHeader('X-Requested-With', 'xhr');
xhr.send();
<img src="about:blank">
Everything works, as when you go into Inspect Element, you see that the src attribute of the <img> tag points to a base64 URL that can load in any browser.
You might want to compress or resize your images before uploading it to server , as they might be large enough to keep the server busy and show the error as most of the time, a 503 error occurs because the server is too busy.
More over the image is SVG so it might render dimesions before completing, hence I'd suggest
Try replacing the SVG with PNG or JPG
Also try for site like https://tinypng.com/ to compress the image size
This might work for you

Razor Page Routing with Friendly Routes not responding

Following https://www.learnrazorpages.com/razor-pages/routing and "Friendly Routes"
With this folder structure:
~Pages / (or "Areas" in last example)
External
PageA
Index.cshtml
Internal
PageB
Index.cshtml
And then I want to add these routes
services.AddMvc()
.AddRazorPages(options =>
{
// Even though above guide states this route it...
// throws exception for "External/PageA" so I have to set "/External/PageA"
options.Conventions.AddPageRoute("External/PageA", "/A");
// throws exception for "External/PageB" so I have to set "/External/PageB"
options.Conventions.AddPageRoute("Internal/PageB", "/B");
});
But all I'm getting is 404 not found. I've tried multilple combinations. I've even followed the Area setup and moved it to areas with the same structure inside the Area folder:
services.AddMvc()
.AddRazorPages(options =>
{
options.AllowAreas = true;
// Also tried "PageA" and "/PageA", "A" and "/A"
options.Conventions.AddAreaPageRoute("External", "/PageA", "/A");
// Also tried "PageB" and "/PageB", "B" and "/B"
options.Conventions.AddAreaPageRoute("Internal", "/PageB", "/B");
});
It's more like the whole convention setup is totally ignored since there has been 0% progress.
The only way that I can access the page is by writing the full folder name. But I don't want this. I want a cleaner routing structure than the folder structure which at the moment seems impossible.
Any suggestions - any ideas?
From the page you linked to:
The [AddPageRoute] method takes two parameters. The first is the relative path to the Razor page file without the extension
You are providing the path to the folder containing the page. You need to add "/Index" to the end of the first argument:
options.Conventions.AddPageRoute("/External/PageA/Index", "A");
The same is true when working with areas. You need to provide the relative path to the actual page, not the folder name:
options.Conventions.AddAreaPageRoute("External", "/PageA/Index", "/A");
This assumes a structure as follows:
Areas
External
Pages
PageA
Index.cshtml

Express loading images relative to url

I'm building a fairly basic webpage using express. However, I'm having some trouble with my image pathways.
This code works fine.
app.use(express.static(path.join(__dirname, "/app/public/")));
app.get("/overview", function(req, res) {
res.render('some-file');
});
Inside of some-file.ejs I have...
<img src="assets/images/picture.jpg">
But what doesnt work is when I have a second url pathway.
app.get("/overview/specific", function(req, res) {
res.render('another-file');
});
<img src="assets/images/picture.jpg">
In this example I'm trying to load the exact same image (in my case its a banner thats reused on every single page). This gives me an error that the image is not found. What I've noticed from the console errors is that the image is being loaded from localhost:3000/overview/assets/images/picture.jpg
I don't understand why express is trying to load the image from whatever the first pathway is (overview in this case). Overview shouldnt be in the pathway!
Can anyone help me out debugging this issue?
Thanks in advance
Try to use /assets/images/picture.jpg.
Add / before the path. Then it will take /app/public/ as a root and be sure that the image will be at :
/app/public/assets/images/picture.jpg
Now wherever you want picture.jpg just pass this absolute path.
We serve favicons dynamically using an ExpressJS redirect, it works very well.
First, we retrieve the site object from memory with a quick lookup based on req.hostname, then send this response:
res.redirect(site.favicon);
The favicon variable could be a static asset on our server, or an asset on another server too. Our front-end code just calls /api/resources/favicon and it will receive the correct link in return.

Loading Background Image to Custom Html page in Web browser control

I have a scenario where I would need to navigate to my own custom html page, when the any request fails. The issue I am facing is I have a background Image which I need to display with the custom html page.
I have implemented the code as follows:
CustomHtmlDoc = "<html><head></head><body background=\"{0}\"; oncontextmenu='return false;'><br><br></br></br><hr><h4 style='font-family:Footlight MT Light;color:red;font-size:20px;'>" + "ErrorMessage" + "</h4><h4 style='font-family:Footlight MT Light;color:red;font-size:25px;'>Please Verify the Configured URL from Dashboard Configuration</h4> <hr></body></html>";
string CustomHtmlDocument = string.Format(CustomHtmlDoc,AppDomain.CurrentDomain.BaseDirectory + "AdministrationUIBrowser\\AdministrationUIBrowserFactory\\ErrorBackground.png");
WebBrowserControlView.DocumentText = CustomHtmlDocument;
I am able to get the error page as background when I try to run the scenario locally. But at the deployed end, I am just getting blank screen with only content without any background Image. Mine is a WPF application.
The DocumentText implementation in Windows Forms does not implement IMoniker and the loaded document will have a base address of about:blank, thus your page cannot find the background image.
You can use a base element to specify the base location for relative urls, or implement a url moniker. There is a sample on implementing a url moniker at http://www.codeproject.com/KB/miscctrl/csEXWB.aspx. Search LoadHtmlIntoBrowser(string html, string sBaseUrl) on the page.
Maybe you can use a Base64 encoded image. Check this service out. i've tested it and it works like a charm.
Hope it helps.
try 100% sure
(Image current folder)
this.webBrowser1.DocumentText =
#"<b>This is an image:</b> <img src='" +
System.IO.Path.GetDirectoryName(Application.ExecutablePath)
+"/ErrorBackground.png'>";