I have been searching here and not finding a solution, so I am asking. How can I serve my static images located in the nodejs server:
public/img
Nodejs (before app.listen()):
app.use("/api", routesIndex);
app.use(express.static(__dirname + '/public/img'));
Angular 10 template:
<img class="center" [src]="quizService.rootUrl+'/public/img/'+quizService.questions[quizService.questionProgress].imageName+'.jpg'">
The [src] resolves to the absolute correct path of:
http://localhost:5000/api/public/img/shark.jpg
But it shows 404 still. Any ideas?
Thanks
There is no need to add path of statically served directory. Just remove '/public/img/'
<img class="center" [src]="quizService.rootUrl + quizService.questions[quizService.questionProgress].imageName+'.jpg'">
You can access the all file of your served directory directly. like:
http://localhost:5000/shark.jpg
Follow the below steps,
your image is at path Public/img/shark.jpg
in your app.js, this should be before any route is created
app.use(express.static(__dirname + '/public/img'));
create a route as below
app.get('/Image/:id', function (req, res) {
// logic to find image based on id passed, we will assume it results in shark.jpg
const filepath = `${__dirname}/public/img/shark.jpg`;
res.sendFile(filepath);
});
Now consume this endpoint from your angular code
localhost:{PORT_NUMBER}/Image/{ID_FOR_SHARK_IMAGE}
I got it working by doing the following:
Nodejs added path:
const path = require("path");
app.use(express.static(path.join(__dirname, 'public/img')));
Then in Angular created a separate assetUrl that omits the "/api" part of the baseUrl:
[src]="quizService.assetUrl+'/'+quizService.questions[quizService.questionProgress].imageName+'.jpg'"
and now my images are served.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.