0

i have created a server.js using node and hosted it at "http://localhost:3000".

when vistited "http://localhost:3000" it returns index.html.

in index.html i have attached a javasript file doggos.js(inside public folder) as script src tag, excutes a function onclick of a button in index.html.

when i clicked the button in index.html i can't see the function getting called.

server.js:

const express = require("express");
const path = require("path");

const app = express();

app.get("/", function(req, res) {
    res.sendFile(path.join(__dirname, "index.html"));
});


app.listen(3000);
console.log("listening on http://localhost:3000");

index.html:
<!DOCTYPE html>
<html>
    <head>
        <title> hello world</title>
    </head>
    <body>
       <h1>doggos</h1> 
       <button id="addNewDog" onclick="">add new dog</button>
       <div id="dogs"></div>       
       <script src="./public/doggos.js"></script>
    </body>
</html>

/public/doggos.js:
const DOG_URL = "https://dog.ceo/api/breeds/image/random";

const dogsElement = document.getElementById("dogs")

function addNewDog(){
    console.log("fetch dog")

    fetch(DOG_URL)
    .then(
        (response)=>response.json()
    )
    .then(
        (processedResp)=>{
            const img = document.createElement("img");
            img.src = processedResp.message;
            img.alt ="cute dog"
            dogsElement.appendChild(img)
        }
    )

}

document.querySelector("#addNewDog").addEventListener("click", addNewDog)

may i know why the function is not getting called ?

Ayyappa Gollu
  • 906
  • 7
  • 16
  • Which node version are you using?? It is advisable to use Axios as fetch API is not implemented in Node. You can read more here : https://stackoverflow.com/questions/48433783/referenceerror-fetch-is-not-defined – Shubham Verma Aug 07 '19 at 11:09
  • Try to remove the empty ´onclick=""´ from your button – Abdelillah Aissani Aug 07 '19 at 11:40

0 Answers0