Serve html directly from Google Cloud Storage and resolve relative links - node.js

I have simple html file, that includes css like this:
<link rel="stylesheet" href="./css/style.css" />
I uploaded this html file and css file too google cloud storage, and set permissions to public.
In my application, written in node js, I want to serve this html file when user access my root page.
In my application I have following code:
public async getPublicFile(opts: IGetFileOpts): Promise<File> {
const bucket = this.storage.bucket(opts.bucket);
return bucket.file(path.join(opts.type, opts.fileName));
}
#Get()
public async serveFile(#Res() response: Response) {
const file = await this.storageService.getPublicFile({
organization: organization,
fileName: 'index.html',
type: 'resources',
});
file.createReadStream().pipe(response);
}
This works as expected. It will server index.html from bucket. However, since this html file have relative link to css file, it will not load css file since it cannot find it.
How can I fix this, so that also css file will be served? Currently I am running this on local computer, but it will be deployed to Google Compute Engine.
I found this link for AppEngine https://cloud.google.com/appengine/docs/standard/go/serving-static-files
Here in AppEngine I can define some handlers like this:
handlers:
- url: /favicon\.ico
static_files: favicon.ico
upload: favicon\.ico
- url: /static
static_dir: public
- url: /.*
secure: always
redirect_http_response_code: 301
script: auto
but as I understand this will not work on local machine.
Also, how do ecommerce companies solves this issues? For example, every shop can have different theme that can be customizable. So I understand that every tenant has own bucket and in tenant bucket, this customizable theme is saved correct? So how I assume that the should have similar issue like me. How do the cope with this situation and how do the handle it?

You are currently trying to reach bucket static css file from an index.html served on your google app engine url. This just can't work out of the box.
There are many options to solve this:
Serve your index.html from the same bucket in public where are your other static files likes css. This has also the benefit of beeing served as CDN which is more efficient. (this is the way I recommand if possible, the only case you cannot do this might be when you want to compute serverside html things in the index.html file before sending it back to the client, but there are great chances this can be done client side)
Build absolute pathes to your css ressources in the index.html "on the fly" or "statically" so the link tag might look like :
<link rel="stylesheet" href="https://bucketurl.com/css/style.css" />
Serve all your content with your app programmatically with a special route that will serve static content by reading files from bucket like you do with your index.html. This should let you keep relative pathes for other static files.

Related

Keeping asset and public path different in vue app for CDN

vue has this option publicPath which lets an app to be deployed on subpath: foobar.com/my-path , making links and every asset accessible via it.
From performance standpoint, I want to enable CDN on my application's assets. How can I use the URL specifically for assets (and not the hyperlinks)?
Example:
./my-path/assets/app.js should become https://my-staging-cdn.com/my-path/assets/app.js
./my-path/url-2.html should remain the same
The configuration below allows me to set the path and assets directory, but not able to figure out how to set cdn URL for assets
module.exports = {
publicPath: ‘/my-path/‘,
assetsDir: 'assets'
}
Cannot do:
publicPath: process.env.NODE_ENV === 'production' ? 'https://my-staging-cdn.com/my-path' : '/my-path/', as it will change the URL in application's links too.
Wasn't able to get the CDN working or assets out of the box. I tried other strategies like pre-rendering or Nuxt, but because of huge number of pages, it wasn't an option.
The objective was to get SEO bots to read rendered page, so I circled out on Rendertron and deployed it's instance and put it in my reverse proxy behind the application. This worked.

Get image from localhost to localhost with express and nodejs

I´m building an app with NodeJs and Angular
The server runs on http://localhost:9000
And the app runs on http://localhost:4200
I have an endpoint whose looks like this http://localhost:9000/users
I use this to retrive all users
The set returned has a key like this { photo: myphoto.jpg }
When I loop the set of data, I want to render the image as this way
<img src="{{ url }}/uploads/users/{{ user.photo }}" alt="{{ user.name }} {{ user.last_name }}"
class="img-fluid shadow-sm avatar100 ml-auto mr-auto d-block rounded-circle">
Where url is http://localhost:9000 and user.photo is myphoto.jpg
The complete route is http://localhost:9000/uploads/users/myfoto.jpg
There is the photo hosted, but the server is throwing an error
Cannot GET /uploads/users/myfoto.jpg
I think, the server is interpreting the URL as API route, and obviously is not declared on routes file.
I want to only retrive the image, how could I do that?
I don´t know what part of my code I can show here. Routes? Front-end? Project structure? Tell me what do you need
With Express, you have to create a route that will handle your image URLs. By default, Express (or the built-in node.js web server) does not serve ANY files. So, it will only serve a file if you create a handler for that specific URL and program that handler to deliver the desired file.
If your images are directly in the file system where the URL base filename matches the actual filename in your server file system, you could use express.static() to create a single route that would serve all your images.
For example, you could use express.static like this:
app.use("/uploads/users", express.static("/uploads/users"));
This would allow a URL requested from:
http://localhost:9000/uploads/users/myphoto.jpg
to be automatically served from the server-side file system at
/uploads/users/myphoto.jpg
It would similarly work for any other matching name in that same directory (or even sub-directories of that directory if the sub-directory was also in the URL).
In general, you don't want to surface internal path names such as /uploads/users all the way back to the user's HTML pages. So, you could do this instead in the HTML page:
<img src="/images/myphoto.jpg">
And, this on the server:
app.use("/images", express.static("/uploads/users"));
This will take any http requests that start with a path of /images and look for the matching filename in /uploads/users on the server, thus not exposing the internals of your server directory structure to the client. It creates the notion of an abstract /images URL that your server can then process and get the images from wherever they happen to be stored on the server.
$ npm i multer
and server add
app.use("/public", express.static("public")); //The folder where the file is located

Angular + node.js, setting the image static path (relative path)

I'm wanting to set the static path with node.js in app.js.
Such as the follow with setting in the public folder:
app.use(express.static(path.join(__dirname, 'public')));
When I use template engines, such as mustache https://mustache.github.io/,
you can set it using a relative path in the template to get a photo a.jpg, like:
<img src="./a.jpg">
When I save a user's photo in the public folder.
In Angular, how do I set the img url relative path from the node.js server folder.
If I save the the full URL in the DB and set the URL in img:
http://120.8.12.8:3000/a.jpg
//or
http://domainname:3000/a.jpg
html:
<img src="http://120.8.12.8:3000/a.jpg">
<img src="http://domainname:3000/a.jpg">
When I change the IP or domain name, the URL will fail.
How can I set it?
I would not save the full path in the database.
Otherwise, I will save information about how to generate the path.
You can have 2 fields in the database, like:
{
"relativePath" : "a.jpg",
"server" : "http://120.8.12.8:3000"
}
After this, and assuming you are consuming the resource from angular, you have several options:
You can directly mix the relativePath and the server in the frontend and create the URL to place in the link
You can hardcode in your angular app what is the "server", and mix that with the relativePath. In this case, in case you migrate the images you just need to modify the frontend
(The best for me). Create an endpoint in the server which gives you what is the host of the image server, call it from your angular app and then create the full link with this response and the relative image path.

ExpressJS static file serve always serves the same file

I have a expressJs setup which looks like this:
// Imports...
const app: express.Application = express();
const port: number = 3001;
const listener = new StatementListenerAPI();
app.use('/listen', listener.getRouter());
app.use('/welcome', router);
if (fs.existsSync('./client')) {
// Running in prod environment with pre built client directory. Serve this.
app.use(express.static('./client'));
}
app.listen(port);
So I have some routers connected to the express app, and at the bottom I declare that the directory client should be served statically. This directory contains an index.html as well as lots of JS, CSS and PNG files. However, no matter which URL I try to access from the express server, it always shows the code of the index.html within the statically served directory. The references to the JS and CSS files used inside the index.html also just return the code of the index.html.
I am using ExpressJS 4.16.3
What am I doing wrong?
Edit: So technically it works if using __dirname + '/client' instead of ./client. What I am now getting is that, when making GET requests from e.g. Postman (therefore "hand-crafting" the HTTP requests), I am always getting the correct results. If I call the resources from within my web browser, it still always shows the website (resolves the index.html). However, now all resources like JS and CSS scripts are being resolved properly, so apperantly Chrome resolves those dependencies properly, I am just wondering why I am still getting the contents of index.html as result when requesting some of the assets or some of the express endpoints via Chrome. API calls via code are working fine, so its only why manual chrome requests show this weird behaviour, at this point I am only asking out of curiosity.
Answer to your original question:
The path supplied to express.static should be relative to the directory from where you launch your node process or an absolute path. To be safe construct an absolute path (ie from the current directory or file). For example:
app.use(express.static(__dirname + '/client'));
Regarding your followup question:
I assume this is because Chrome uses heavy caching and it thinks this folder should return the html file. You can try and reset all caches in Chrome, or just for the page.

express does not include assets

I'm trying to load assets to my EJS file using express and it does not work. I just get message
Cannot GET /assets/main.css
Even I made loader in my main app:
app.use(express.static(path.join(__dirname, './assets')));
and after printing the path I see that its correct and the files exsists. So after using
<link href="assets/main.css" rel="stylesheet"> I can't reach the file. Where the problem could be?
See Serving static files in Express.
Right now, your app.use(...) statement is saying: I want the directory ./assets to be served whenever I navigate to my app, in other words, when I open my browser to http://localhost, serve whatever is in the folder ./assets.
You are then trying to access the file main.css at http://localhost/assets/main.css. It isn't there, it's at http://localhost/main.css.
You have 2 options:
Change your <link> tag to point to where the asset actually is:
<link href="main.css" rel="stylesheet">
Change your app.use() to host the ./assets folder at a different endpoint:
app.use('/assets', express.static(path.join(__dirname, './assets')));

Resources