Unable to set a background image sourced from API data onto a div element in Node.js

I am having trouble setting a background image to a div using the API-provided link in my CSS. Even when trying to directly access the image in Chrome, nothing seems to happen. Here's the code snippet:

function getData(responseData) {
    var poster = responseData.results[0].poster_path;
    appendToDom(poster);
}

function appendToDom(poster) {
    var aPoster = $('<div>');
    var movie_poster = 'url("' + poster + '")';
    console.log(movie_poster);
    aPoster.css({
        'float': 'left',
        'margin': 10,
        'margin-left': 37,
        'margin-top': 20,
        'width': 200,
        'height': 300,
        'font-size': 36,
        'color': 'black',
        'background-size': '200px 300px',
        'background-image': movie_poster //'url("./../images/question.jpg")'
    })
    $(main).append(aPoster);
}

Upon checking my console, the URL ("/rwn876MeqienhOVSSjtUPnwxn0Z.jpg") is being returned as expected. I'm using The Movie DataBase API for this operation.

Appreciate any help provided in advance!

Good news! I've managed to resolve the issue. Below is the updated JS file with a list of posters linked to specific names.

$('#search').keypress(function(e) {
        if (e.which == 13) {
            var movie = $('#search-input').val();
            $('form#login').submit();
            console.log('onclick fun', movie)
            makeCall(movie);
            return false;
        }
    });

    function makeCall(aMovie) {
        console.log('makecall', aMovie);

        link = url + aMovie;
        console.log(link);
        $.ajax({
            method: "GET",
            url: link,
            success: function(data) {
                console.log("the data -->", data);
                getData(data);
            },
        })
    }

    function getData(responseData) {
        for (let i = 0; i < responseData.results.length; i++) {
            var poster = responseData.results[i].poster_path;
            appendToDom(poster);
        }
    }

    function appendToDom(poster) {
        var aPoster = $('<div>');
        var movie_poster = 'url("https://image.tmdb.org/t/p/w1280' + poster + '")';
        console.log(movie_poster);
        aPoster.css({
            'float': 'left',
            'margin': 10,
            'margin-left': 37,
            'margin-top': 20,
            'width': 200,
            'height': 300,
            'font-size': 36,
            'color': 'black',
            'background-size': '200px 300px',
        })

        if (poster === null) {
            aPoster.css({
                'background-image': 'url("./../images/question.jpg")'
            })
        } else {
            aPoster.css({
                'background-image': movie_poster //'url("https://image.tmdb.org/t/p/w1280/rwn876MeqienhOVSSjtUPnwxn0Z.jpg")' //'url("./../images/question.jpg")'
            })
        }
        $(main).append(aPoster);
    }

Answer №1

   This is an example of an HTML file.

 <!Doctype html>
    <html>

    <head>
      <Title>Image Background</Title>

    </head>

    <Body>
      <main></main>
      <script src="https://code.jquery.com/jquery-3.2.1.min.js" integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4=" crossorigin="anonymous"></script>
      <script>
        $.getJSON("http://127.0.0.1/json", function(result) {
          console.log(result);
          getData(result);
        });

        function getData(responseData) {
          var poster = responseData.poster_path;
          appendToDom(poster);
        }

        function appendToDom(poster) {
          console.log(poster);
          var aPoster = $('<div>');
          var movie_poster = 'url("' + poster + '")';
          console.log(movie_poster);
          aPoster.css({
            'float': 'left',
            'margin': 10,
            'margin-left': 37,
            'margin-top': 20,
            'width': 200,
            'height': 300,
            'font-size': 36,
            'color': 'black',
            'background-size': '200px 300px',
            'background-image': movie_poster //'url("./../images/question.jpg")'
          })
          $("main").append(aPoster);
        }
      </script>
    </Body>

    </html>

Here is a simple backend setup.

var http = require('http');
var fs = require('fs');

var server = http.createServer(function (req, res) {
  console.log(req.url);

  if (req.url == "/json") {
    var j = {
      poster_path: "./public/images/foxxi.webp"
    }
    console.log('sending json');
    res.end(JSON.stringify(j));
  } else if (req.url == "/public/images/foxxi.webp") {
    fs.readFile("./public/images/foxxi.webp", function (err, image) {
      res.write(image);
      console.log('sending image');
      res.end();
    });

  } else {
    fs.readFile("po.html", function (err, html) {
      res.write(html);
      console.log('sending html');
      res.end();
    });

  }

});

server.listen(80);

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

Bring the element to the top of the page by clicking on the anchor within the element or anywhere within the specified div ID

I am looking to implement a functionality where the page scrolls to the top of the navigation div ID when a link inside the navigation div is clicked, or ideally even when clicking anywhere within the div itself that contains the navigation links. After r ...

Using JQuery to handle multiple 'or' conditions within an if statement

Is there a way for me to monitor if someone clicks on any of the IDs provided (#transfers, #shopper, #tasks) and then trigger a click event on another button to activate it? <script> $(function() { function updateServicesGroup(prop, value) { ...

Implementing a document update event using jQuery

On my WordPress site, I am using a responsive lightbox plugin. When an image is clicked, it opens a popup box with the ID fullResImage. Now, I would like to incorporate the Pinch Zoomer function to it. Do I need to bind a function for this, or is there a s ...

Form validation using jQuery and AJAX

I've implemented validation in my ResetPassword function and it seems to be working fine. However, I'm facing an issue where the ResetPassword function stops working once the validation is added. Can someone guide me on how to resolve this issue? ...

User retrieval failed following successful passport authentication

After a successful authentication, the user is directed to the "/profile" route, as demonstrated in the code snippet below. app.get( "/auth/google/callback", passport.authenticate("google", { successRedirect: "/profile", failureRedirect: " ...

What is the procedure for enabling users to include parameters in an API?

Is there a way for users to input parameters in an API? For example: http://localhost:8080/amk_codes?collada_north=1.361692308&collada_east=103.8527273 Here are the code snippets I currently have: app.get("/amk_codes", async (req, res) => { const ...

Are there any available NPM packages specifically for integrating with QuestDB?

Just started using QuestDB and I'm curious if there is an npm package available for it. I found a package on npmjs.com/questdb, but it appears to be empty. Can someone confirm if there is indeed an npm package for QuestDB? Thank you! ...

Is there a way to efficiently use AJAX and PHP to iterate through JSON data and save it to a new JSON file

I have created a simple movie editor with a sidebar where users can drag and drop elements. On the right side, users can edit these elements as they wish and save the data to a JSON file. When the user clicks save, I want it to create a new file and save t ...

Dynamically loading Jquery tabs in AngularJS can enhance user experience and

I need to implement a feature that loads tabs from an array using AngularJS. $scope.hods = [ { leader_id: 1000321, staff_id: 1000321, longname: "Ooi Kok Hong", username: "ANDREW", team_role: "HOD", importance: "1", active:true }, { leader_id: 100 ...

How would you go about creating a VueJS component that displays a table with a set number of columns and automatically distributes the cells within them?

Hey there! I'm currently working with a VueJS component that looks like this: <template> <div> <table> <tbody> <tr v-for="(item, index) in items" :key="index"> <t ...

Issue with Material UI text input field in Appbar functionality not functioning as expected

I am attempting to add two text input fields for username and password to the right of the AppBar using the code below. However, I am not getting any output. const CustomAppBar = () => ( < AppBar title = { < span style = { styles.title } > T ...

My efforts to resolve the issues in my code have been ongoing, but unfortunately, I have been unable to find a solution

I'm struggling to insert my contact form code into the contact tab without it interfering with the tab bar. I want the form to appear in the middle of the page when the tab is clicked. I've tried various placements for the code but none seem to ...

Obtain data with matching JSON values in a REACT application

Recently, I received a JSON file that looks something like this: [ { "symbol": "A", "name": "Agilent Technologies Inc", "exchange": "NYSE", }, { "symbol": "AAC ...

What is the process for transforming the outcome of a Javascript function into a webpage containing solely a JSON string?

I have a specific requirement where I need to fetch a URL and ensure that the only content displayed on the page is a JSON string. For instance, let's say I created a basic function called getDayOfWeek() to determine the current day of the week. The ...

What is the best way to specify a type for an object without altering its underlying implicit type?

Suppose we have a scenario where an interface/type is defined as follows: interface ITest { abc: string[] } and then it is assigned to an object like this: const obj: ITest = { abc: ["x", "y", "z"] } We then attempt to create a type based on the valu ...

Displaying separate items onto a webpage based on their unique identifiers

Currently, I am in the process of developing a JavaScript web application that retrieves input from a user (specifically the name of a music artist) and then produces a list of related artists along with their most popular songs, all thanks to information ...

Harnessing Spread Syntax with Map and Filter Operations

Recently stumbled upon a fascinating problem that I couldn't wait to share with all of you. Here is the question at hand: [...[0,1,...[-1,0,1].map((x)=> x+1)].filter((x)=>x)),7] I managed to successfully solve the initial section up to the fi ...

troubleshoot using Visual Studio Code

Here's the scenario: I need to debug a project using VS Code. The project is usually started by a batch file and then runs some JavaScript code. Now, I want to debug the JavaScript code, but I'm not sure how to do that. If anyone has any instruct ...

Tips for importing the mongoose-long plugin using the ES6 method

How can I rewrite the given import syntax into ES6 import format? import mongoose from 'mongoose'; import 'mongoose-long'(mongoose); import { Types: { Long } } from mongoose; ...

Utilize the Google reverse geocoding API to convert latitude and longitude values from JSON into a dynamic variable

I have been utilizing the NPM Geocoder to convert locations into latitude and longitude coordinates, but I am struggling with extracting the lat and long values from the output. Below is the JSON data, and my goal is to store the values on lines 59 and 60 ...