Struggling to pass images from express to Angular6

Snippet of Node.js code

    app.use('/static/images',express.static(path.join(__dirname,'images')))

   Folder Structure 
    |-root 
    | -images 

When attempting to fetch data in my Angular6+ application, I am utilizing the following code:

      this.productService.dataSubject.subscribe((val)=>{
          console.log(val,"we are from Trail Zoom Component",Config.URLS.images+val['product']['imageUrl']) 

          this.productImg = Config.URLS.images+val['product']['imageUrl']

Upon checking my console, I can see:

{product: {…}} "we are from Trail Zoom Component" "http://localhost:3000/static/images/image-1612722550428.jpeg"

To ensure the image is present in the images folder, I checked and confirmed it is there.

However, when trying to access the image at "http://localhost:3000/static/images/image-1612722550428.jpeg", it appears encrypted.

Please refer to the link for a visual representation: https://i.stack.imgur.com/7NKBB.png

I also attempted to set headers for the image but the issue persists. Here is the modified code snippet:

app.use('/static/images',express.static(path.join(__dirname,'images'),{
    setHeaders: setCustomCacheControl
}))

function setCustomCacheControl (res, path) {
      res.setHeader('Content-Type','image/jpeg')
    }

My additional headers:
app.use(bodyParser.urlencoded({ extended: false }))
 
// parse application/json

    app.use((req, res, next) => {
        res.setHeader('Access-Control-Allow-Origin', '*');
        res.setHeader('Content-Type', 'application/json');
        res.setHeader(
          'Access-Control-Allow-Methods',
          'OPTIONS, GET, POST, PUT, PATCH, DELETE'
        );
        res.setHeader('Access-Control-Allow-Headers', 'Content-Type, Authorization');
        if (req.method === 'OPTIONS') {
          return res.sendStatus(200);
        }
        next();
    });
    app.use(bodyParser.json())

Answer №1

I started to feel better about myself after successfully resolving the problem by updating the path from /static/images to /static/images/

app.use('/static/images/',express.static(path.join(__dirname,'images'),{
    setHeaders: setCustomCacheControl
}))

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

How can I sync changes between two variables in node.js?

Is there a method to create a shared variable in JavaScript? Here is an example of what I am attempting to achieve: var id = 5; var player = new Player(id); var array1[0] = player; var array2[0] = player; array1[0].id = 8 console.log(array1[0]); // ...

Querying the sqlite-3 database fails to transfer data to a JavaScript array

I encountered an issue while working on a NodeJS project that involves fetching film names and descriptions from an Sqlite-3 file when a user sends a GET request to /films. For some reason, I am unable to push the object to an array properly. Despite my ...

Avoid including sensitive credentials in the AJAX response when utilizing Node Express

Consider this scenario: exports.listUsers = function(req, res, next){ userModel.find(function(err, users){ if(err){ return next(err); } return res.send(users); }); }; When sending an array of user objects to th ...

Prefixes for logging - Consider using the not-singleton technique or another approach

I am currently developing a logging helper for Node.JS that includes several exported functions such as error and warn. For instance, I have two other scripts called test1 and test2 which make use of this "module". When initializing my logging module us ...

No matching record found with the given id in Mongoose

I'm attempting to retrieve a record by its id but I'm facing some issues. var id = req.param('id'); var item = { '_id': id } videos.find(item, function(error, response) {}); Even though I have provided a valid id, it&apo ...

Ways to verify and incorporate https:// in a URL for a MEAN Stack application

When extracting the URL from API data, my code looks like this: <div class="row copy-text"> <a href="{{copy.Url}}" target="_blank" style="text-decoration: underline !important;">{{copy.Title}}</a> </div> I am interested in ve ...

Integrating Spartacus: Unresolved peer dependencies detected in package installation

Just set up a fresh project using the latest Angular CLI 13.3.6 (node 16.15.0, yarn 1.22.15). I'm attempting to incorporate Spartacus as detailed in this guide: but when I execute ng add @spartacus/schematics@latest I encounter the following error: ...

Angular 6's Select feature is failing to properly update user information

We are currently facing an issue with our user profile edit form. When users try to update their information by changing simple input fields, the changes are reflected successfully. However, when they make selections in dropdown menus, the values do not ge ...

Utilize HTML or JavaScript to make a POST request with Express

Recently, I decided to dip my toes into the world of back-end development using express for the first time. I came across a situation where I needed to make a POST request from an html/js file, and initially used Jquery to accomplish this task. However, I ...

Is there a possibility that typescript decorators' features will be polyfilled in browsers lacking ES5 support?

According to the typescript documentation, a warning is issued: WARNING  If your script target is lower than ES5, the Property Descriptor will be undefined. If the method decorator returns a value, it will act as the Property Descriptor for the method. ...

Synchronize the completion of multiple promises in ExpressJs before sending a response

My POST API contains some logic that needs to wait for all promises to finish before sending the response. However, I'm facing an issue with making my server wait using await Promise.all(tasks); I've tried various approaches and even used librar ...

Setting up Node NPM proxy authentication - what's the process?

Just diving into the world of Node and attempting to install TypeScript with this command: npm install -g typescript Encountering this error message: If you are behind a proxy, please ensure that the 'proxy' config is set correctly. I've ...

Is pl/pgsql block code supported by postgres-nodejs?

I am attempting to define a custom UUID variable that can be utilized across multiple queries within a transaction. Initially, I attempted using a JavaScript variable which ultimately defeated the purpose of declaring the variable on the server side. The ...

Selenium for uploading a file on a Mac device

I am facing a challenge when trying to upload a file on my MAC using selenium with Java. The button I need to interact with does not have an input tag, so I attempted to use robot script and even apple script but haven't been successful. Is there anyo ...

terminate the default browser using Node.js

When using nodejs, the open package allows you to open a default browser. However, what is a good way to programmatically close the default browser using nodejs or bash on Ubuntu? var open = require('open'); open('https://www.youtub ...

Create the next app with updated files by rebuilding it while utilizing express as the server

I'm currently utilizing the combination of Next.js and Express.js in my project. In this setup, Express handles all the routing tasks instead of Next.js. For a smoother development experience, I require a process where whenever a file is modified, Ne ...

How to ensure folder creation before uploading in Express.js

Is there a way to ensure the creation of a folder before uploading an image to prevent getting an ENOENT error? Here is the code I have been using: module.exports = function(router){ router.post('/result', directory.tmp, uploader.single, f ...

Is Node.js going to continue to provide support for its previous versions of node modules?

I currently have a website that relies on the following dependencies. While everything is working smoothly at the moment, I can't help but wonder about the future support of these packages by node.js. I've looked into the legacy documentation of ...

Randomly, an AJAX request sent from Internet Explorer 11 to a node.js server operating behind an Apache proxy may abruptly terminate

When using angular on a webpage, a get request is initiated to retrieve json data after a user action. The issue arises when attempting this request on Internet Explorer 11, as it fails randomly while working smoothly on Firefox. Below is a screenshot of t ...

The issue persists in Angular 5 and asp.net MVC where the ID number continues to increase despite being deleted

Currently, I am using Angular 5 (VS CODE) for the front-end and asp.net mvc/entity framework (VS2017) for the back-end. My CRUD methods are functioning properly; however, I have encountered an issue where the ID of a newly created row keeps increasing even ...