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

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.

Related

How to download a file from server in react?

I have a Node.js backend that sends an icon image to a React frontend. Initially, I encode this image as a Base64 string and store it directly in the database. I created an api that returns this string to the frontend. However, I read that it is bad to store it in the database, so I re-wrote the api to store this string in the server as a json file and now my api returns the absolute path to this json file. However, how is the React frontend supposed to retrieve the file? Is it possible to use the absolute path or do I have to create another api to return a file object ? If so, how do I do that?
I'm a newbie at both react and node.js so any help is appreciated.Thanks.
EDIT: I stored the file path as __dirname of where my code resides + filename.I'm getting cors error when accessing that url
Use Express to share out that folder as such-and-such.
Suppose you keep your files in a folder called files, just off the root. And suppose your server structure looks roughly like this:
- backend
- app.js
- frontend
- Components
- Routes
- public
- dev
- index.html (your template file)
- files
- myimage.png
In your root js file (app.js? server.js? index.js?):
const app = express()
app.use('/static', express.static('public'));
app.use('/files', express.static('public/files'));
Then, in the frontend code:
<img src='/files/myimage.png' />
By the way, there is no problem storing images as base64 in your database... but every database backup will also backup those images. If you have a small database, no worries. However, if you have a LOT of images, especially very large images, this will make your database (and backups) unnecessarily large and unwieldy.
Everything depends on your use case.

cannot reach a file on server though I exposed using express

In my project I need to store some text files dynamically and end user should be able to download them from browser. I know the best way is using object store like MINIO or S3 but unfortunately the only way I have is to use in memory storage. So what I am trying to do is: I made a public folder and I exposed it using the following code:
var express = require('express');
var app = express();
//setting middleware
app.use(express.static( 'public')); //Serves resources from public folder
var server = app.listen(5000);
it is as simple as that. Then for testing just to make sure I can download and reach a file I created a public folder with t.txt file in it and when I try:
http://localhost:5000/public/t.txt
I get
So why am I not getting it? Also is what I am trying to achieve will be a good match to scenario and is it doable at all?
When you're not specifying a path in app.use(), your app will serve the contents of the directory you're pointing to in express.static() on the root path. Try this:
http://localhost:5000/t.txt
That said, if you want it to be accessible at /public/t.txt, just specify the path:
app.use('/public', express.static('public'))
At first use the following line of code:
app.use(express.static(__dirname+'/public'));
This means that your home directory for static HTML pages is in the "public" folder. Note that the "__dirname" points to the directory of the current js file.
After that, call the following URL from the browser or POSTMAN:
http://localhost:5000/t.txt
As you can see, there is no need to write http://localhost:5000/public/t.txt referring to the "public" folder because you have already specified that in the app.use line.

How can i display images in angular app while images are stored in node.js server uploads folder?

I have a node.js server(separate directory) where i am saving files in uploads folder and saving image path in db. I have following directory structure in my node.js server
node_modules
src
uploads
|category-name-folder
|image-name.jpg
|category-name-folder
|image-name.jpg
package.json
i am saving image path in db like this uploads/category-name/image-name.jpg.
Now i want to display all images in angular app. So please guide me how can i display these images to angular app? Should i send image paths to angular app via an Api ? if yes so what complete url should i send to angular app and what url should i bind in angular app img src?
Note : I have a separate directory structure of client app (angular)
In server side(Nodejs), serve the uploads folder statically. To Angular send the image path and give it as a source for images.
<img [src]="imagePath">
The image source should be something like 'YOUR_DOMAIN/uploads/filename'. This is required for your case since you are providing the angular index.html in a separate domain(server).
Use this link if you are using express
Basically, what you need to do is create a GET endpoint in your node server to return the image, something like:
[GET]images/{folder}/{imageName}
And instead of saving the image path, you can save the URL to call that endpoint:
uploadedObj {
url : config.domain + 'images/' + folder + '/image.jpg'
}
Then when you get the data in your angular, you put that value directly in the image src.
<img src="{{ upload.url }}" *ngFor="let upload of uploads"/>

Relative path of static files express/react

I'm running my react client on localhost:3000 and my express server on localhost:4000, and I have a static folder in my server with images.
I'm trying to save the image path to a MySQL database, and use that in React as an img src, but can't figure out how to do it without hard coding the path. For example, localhost:4000/images/img1.jpg works, but if I change the host name tomorrow, all of my db data becomes irrelevant.
Three answers:
In react you can fill props by joining a constant string and a variable. Just save the /images/img1.jpg in the database instead of full URL. Then in react do <img src={'http://localhost:4000/' + imagePathFromDB} />. When you change the server just change it once.
You can create a simple SQL query to update your DB to be relevant this is the beauty of SQL database.
For e.g.
update images set path=replace(path,'localhost:4000','newdomain.com')
Voilla!
If you using create-react-app you can serve the frontend and backend from the same domain using the proxy parameter. And then just save in the database /myimage.jpg and in React <img src={myVariable} />

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

Resources