Get the image data from a Nuxt 3 REST API endpoint

I've developed a straightforward API that fetches an image, performs transformations on it, and is supposed to return the modified image. Currently, I can only return a base64 string representation of the image. However, I'm unsure how to return it as an actual image that would effortlessly render in the browser.

For example, if I input this link into the browser, the image displays correctly. What I aim for is to prepend my own URL (e.g. for testing

https://localhost:3000/api/images/remote/[URL]
) and have it exhibit the image in the same manner.

The code snippet below illustrates how I currently retrieve the base64 string of the new image:

const response = await fetch(URL)

// perform transformations

const arrayBuffer = await response.arrayBuffer()
const buffer = Buffer.from(arrayBuffer)
const base64 = buffer.toString("base64")

return base64

Though this approach allows me to successfully display the base64 string within an <img> tag, I am uncertain about how to convert it into an actual image object that will render directly in the browser without being displayed as a base64 string.

I understand that the solution might entail properly setting headers on the response and returning a blob, but despite thorough research via Google, I haven't been able to find a clear answer.

Answer №1

Are you talking about the /server directory within your Nuxt project for handling API requests? I had to create a server route to fetch thumbnails that required an access token:

// In the file: ../server/api/thumbnail/[filename].get.js
export default defineEventHandler( async (e) => {
    const { filename } = e.context.params;

    try {
        const token = await getToken();

        const blob = await $fetch(`${BASE_URL}/resources/thumbnails/${filename}`, {
            headers: {
                "Token": token
            }
        });

        const arrayBuffer = await blob.arrayBuffer()
        const buffer = Buffer.from(arrayBuffer, 'base64')

        return buffer;
    }
    catch (err) {
        console.error(err);
    }

    return {};
});

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

"An issue with the colyseus server has been detected within the JavaScript code

I have written some code but it seems to be causing errors. const colyseus = require("colyseus"); const http = require("http"); const express = require("express"); const port = process.env.port || 3000; const app = express(); ...

Automate the manipulation of a dynamically-generated table using Selenium and javascript

Is it feasible to use Selenium to select a menu item created primarily with JavaScript? The HTML tags for this table are only visible in the view source. <table id = "table_id"> <tr> <td> <script> *** </script> </ ...

Making an API request using jQuery

I am currently working on creating a .js file that will send data to an external API, wait for a response, and then interpret the results. The external API I am using is XML-based and requires an HTTPS Post request with the XML content in the body (content ...

Impose a delay between the execution of two functions in React.js

Looking for a way to introduce a forced delay between two consecutive function calls. Essentially, what I want to achieve is: a // call func a delay(100) // pause for 100 ms b // call func b Is there a method to accomplish this? Update: attempted a() ...

Run several asynchronous HTTP requests in the background within a Chrome extension

I am facing a situation where I need to make multiple ajax requests through a Chrome extension and display the successful results in the popup HTML of the extension. I have created an array of URLs and loop through them to perform the ajax requests. Every ...

Extending the Angular Date filter with translation capabilities

During the development of an application that allows users to select a date, I encountered an issue with the translations of the date filter. To resolve this, I implemented the following solution: Extended the date filter functionality Substituted the ...

Guide on making jQuery color variables?

Is there a way to achieve CSS variable-like functionality with jQuery? For example, creating reusable CSS attributes in jQuery instead of using SASS variables. Imagine if I could define a variable for the color black like this: I want to make a variable t ...

What is the best way to save a large array to a .txt file in node.js?

It seems that using fs.writeFile is the obvious solution. However, after reading the response to this question, it appears that a Stream technique might be more appropriate. In an attempt to delete a line from a text file by converting it to an array, I ...

Looking to extract data from various checkbox options and save it as an array variable

For a coding boot camp assignment, I'm working on a modal that includes options for the days of the week. My approach involves using Jquery .each and CSS :checked to retrieve the values assigned to each input. However, every time I attempt to log the ...

Tips for resolving issues with the carousel container in bootstrap?

Is there a way to adjust the carousel box container in Bootstrap so that it remains consistent even with images of varying sizes? Currently, the box size changes based on the image dimensions when sliding through the carousel. Sample Code: <h1>Caro ...

How can I use lodash to iterate through and remove whitespace from array elements?

I am currently working on a project involving demo lodash functionality, and I have encountered some unexpected behavior. Within an array of cars, there are various non-string elements mixed in. My goal is to iterate through each element of the array, rem ...

There is an issue with my HTML due to a MIME type error

I am currently facing an issue with my project. I have developed a node js server and now I want to display an HTML file that includes a Vue script loading data using another method written in a separate JS file. However, when I attempt to load the HTML f ...

Node.js version 12.7 does not have the ability to support dynamic keys within objects

According to what I've read about ecma6, it should allow for dynamic key objects. I recently upgraded my node to version 0.12.7, but I'm still encountering an error. node /var/www/games/node_modules/app.js /var/www/games/node_modules/app.js ...

Making AJAX requests to retrieve data from a JSON database array, then utilizing the CSS visibility property to conceal HTML elements dynamically

As a enthusiastic beginner, I'm facing a challenge that seems to have no easy solution. Can someone please assist me with this: How can I assign all the ids from a JSON database to the variable dotContainer, in order to hide all corresponding HTML id ...

Dealing with functions that may not consistently return a promise

When dealing with a situation where a function does not always return a promise, how can it be best handled? The complexity of my current code prevents me from providing a detailed explanation, but essentially, the issue involves checking a condition and t ...

Is there a way to automatically scroll to the last dynamically added div?

Within the chat.html file, I have included a div tag and implemented a script that dynamically adds rows to the div when a button is clicked. In another file named list.html, I have inserted an iframe tag with the src attribute pointing to chat.html. Howev ...

Define the position of a scrolled area within an HTML document to create a

In my current project, I have a scrollable area that highlights the selected div in gray. The HTML is written using Ember (hbs) and includes code to handle this functionality. Below is an example of how the div looks: https://i.sstatic.net/T2Lur.png Here ...

Calculate the total value of selected checkboxes in every row of the table

I am looking to calculate the total sum of checkboxes for each row in a table Javascript : For Sum $('input[type="checkbox"]').change(function() { var total = 0; $('#mytable tr').each(functi ...

Error: Kinetic.js cannot upload image to canvas

There must be something simple that I'm missing here. I've checked my code line by line, but for some reason, the image just won't load. var displayImage = function(){ var stage = new Kinetic.Stage("imgarea", 250, 256); var layer = new ...

Experiencing the Pause: A Fresh Take on

I'm currently using this slideshow for a project, and I need to understand if it's possible to resume its interval. The current issue is that when you hover over the slideshow, the progress bar stops. But once you remove the mouse, it continues f ...