transmitting a picture from the server to the client using a REST API

My goal is to send an image from the server (currently stored in local storage) to the client. Below is a snippet of my code:

exports.get_icon = (req, res) => {

  App.findOne({name: req.body.name}, (error, application) => {
    if(error){
      console.log(error);
    } else{
      console.log(application);

      res.status(200).send(application.iconImage) //!!need to do something here
    }
  })
}

In this function, I intend to retrieve the path where the image is stored and then transmit it to the client. Currently, the server sends the path of the image instead of the actual image. For example, it might be like this uploads/Twitter/icon.png. So how can I successfully send the image from the server to the client with the understanding that application.iconImage provides the path of the image?

Answer №1

One useful feature in Express is the ability to send a file using its file path.

res.sendFile

app.get('/getImage/:id', (req, res) => {
    res.sendFile(filepath);
});

However, it is recommended to send the file path instead of the actual file itself for best practices.

app.get('/getImage/:id', (req, res) => {
   res.send({ img: filePath });
})

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

What is the reason for `then` generating a new promise rather than simply returning the promise that was returned by `

I've been curious about why, in a situation where the onFulfilled handler of then() returns a promise p2, then() creates a new promise p3 instead of simply returning p2? For example: let p1 = new Promise(function(resolve, reject) { resolve(42); ...

Button with a Jquery icon design

Hello, I am currently working on implementing an icon button that can collapse and expand text. Although I have successfully implemented the logic for collapsing/expanding, I am facing difficulties in creating the actual icon button. The theme I am require ...

The issue with Bootstrap 4 toggle not correctly hiding the following div

I am trying to hide one div when the other div is displayed using Bootstrap code. However, both divs are currently displaying and my code is not working as intended. If anyone can provide assistance, it would be greatly appreciated. <link rel="st ...

JavaScript Error: value.toUpperCase is not a valid method

I am attempting to implement a script that allows users to filter rows in a table based on the value they input. After updating a row, the page refreshes and all rows are displayed again. I am looking for a way to maintain the filtered rows after the refre ...

Disappear the loading icon once all children have finished rendering

I'm facing a minor issue with rendering in React and struggling to find a solution. Here's what's happening: My component acts as a wrapper for multiple entries, like this: class MyWrapper extends Component { renderItems() { return ( ...

Leverage the power of React by utilizing SVGR to easily integrate SVG files

Wondering if there's a way to bring in an SVG file from my public folder and use it as a React component like this: import { ReactComponent as MySvg } from '/assets/svg/mysvg.svg'; const MyComponent = () => { return ( <div> ...

Initiating a request to a server located remotely

Having an issue trying to proxy a request from my angular client app using express.js as middleware. app.use('/v1', function(req, res) { var url = process.env.API_URL + req.url; console.info('Proxing to: ', url); var r = null; ...

How can you leverage JavaScript's map() method to manipulate an element within an array using string functions?

I am attempting to achieve the following. strs = ["one", "two"]; let sorted_str = strs.map((s) => [s.sort(), s]); Basically, my goal is to create a new array of arrays where each nested array consists of the sorted string from the o ...

What could be causing the lack of value appearing after I clicked the button?

Setting the value for the array of images as an empty string does not return the expected result. When I move one of the 4 images and click the button, I anticipate a new array with the information of one of the four images including src, x, and y coordina ...

Creating interconnected select boxes based on JSON data to display parent-child relationships in a cascading manner

A dynamic creation of chained select-boxes has been implemented based on JSON data fetched from the server. In this cascading process, each select-box is an object with specific properties: Parent Attribute: The name of the parent object for the current ...

The process of prioritizing specific elements at the top of an array when ordering

In my array, I want to prioritize specific items to always appear at the top. The API response looks like this: const itemInventorylocationTypes = [ { itemInventorylocationId: '00d3898b-c6f8-43eb-9470-70a11cecbbd7', itemInvent ...

Find the name of the region in the user's query

I've implemented the weather-js npm module (weather-js) to retrieve weather information for a specific region. While everything is functioning correctly, I'm looking to customize it based on user input. The module currently only accepts region ...

When you press the button, increase the number by one

Is there a way to increment the number by 1 on click event? I'm not sure what's the best approach for this. In my render(): {this.state.posts.map((post, i) => <div key={post._id}> <span>Votes: {post.votes}</span ...

The isolate scope variable is becoming undefined within the link function

When working with a directive that takes a data object and a function in its isolate scope, I encountered an issue. Inside the link function, I declared a method to be triggered on a button click event. The problem is that while the value passed to the me ...

Having trouble configuring Travis; crashes just before installation begins

Today I attempted to set up Travis on my GitHub project but encountered a few roadblocks (refer to the screenshot). I experimented with different configurations in .travis.yml, such as the one below: language: node_js node_js: - "8.11.2" sudo: false b ...

Having trouble with less.modifyVars not functioning properly in Visual Studio?

I attempted to dynamically change the LESS variable using HTML within an AngularJS function. The code worked fine on XAMPP with simple HTML and CSS, but when I transferred it to an enterprise app in Visual Studio, it stopped functioning properly. While the ...

Warning: Please note that the command 'vue init webpack my-project' is deprecated and may not be supported in future

My Objective: I aim to start a Vue.js project by executing the command vue init webpack myproject Expected Outcome: The installation of all dependencies without any fatal errors, and being able to run the project using npm dev run, accessible at http://lo ...

Next.js 14 useEffect firing twice upon page load

Having an issue with a client component in next js that is calling an API twice at page load using useEffect. Here's the code for the client component: 'use client'; import { useState, useEffect } from 'react'; import { useInView ...

Transform unidentified individuals into authenticated users using Firebase Authentication for Google

Currently, I am integrating Firebase Auth with VueJS and facing the challenge of converting an anonymous authentication user to a registered user using Google. I have implemented the following code snippet from a reference: fromAnonymousToGoogle: funct ...

Tips for retrieving the text enclosed within a <span> tag using jQuery

I am new to jQuery and came across this code online for a questionnaire. I want to save the selected options but I am not sure how to do it. " $.fn.jRadio = function (settings)" What is the purpose of this setting? " var options = $.extend(_de ...