Something seems off with my code. It's causing a barrage of errors to appear on the browser

JavaScript is a whole new world for me, and I'm struggling with all these errors.

The goal here is simple: click the "generate" button, and under "Most Recent Entry," display the current temperature for the entered zip code, today's date, and the user's input on how they're feeling.

However, when I tested it in the browser, a flood of errors popped up, leaving me puzzled. I've got node, cors, body-parser, and express installed, but they all show vulnerabilities - not sure if that's causing some functions to fail.

This is what shows up on the console after entering a zip code and some text: browser console errors

On the server side:

/* Initializing an empty JS object */
projectData = {};

/* Setting up Node environment */
const express = require("express");
const app = express();

/* Dependencies */
// Middleware
const bodyParser = require("body-parser");
app.use(bodyParser.urlencoded({extended: false}));
app.use(bodyParser.json());

const cors = require("cors");
app.use(cors());

/* Initialize the main project folder */
app.use(express.static("website"));

/* Create server */
const port = 8000;
app.listen(port, listening);
function listening() {
  console.log(`Server running on port ${port}`);
};

/* GET route */
app.get("/all", returnData);
function returnData(req, res) {
  res.send(projectData);
};

/* POST route */
const data = [];

app.post("/addData", addData);
function addData(req, res) {
  let newData = request.body;
  let newEntry = {
    temp: newData.temp,
    date: newData.date,
    content: newData.content,
  }
  data.push(newEntry);
};

On the client side:

/* Asynchronous POST */
const postData = async (url = "", data = {}) => {
    console.log(data);
    const response = await fetch(url, {
        method: "POST", 
        credentials: "same-origin",
        headers: {
            "Content-Type": "application/json",
        },       
        body: JSON.stringify(data), 
    });

    try {
        const newData = await response.json();
        console.log(newData);
        return newData;
    } catch(error) {
        console.log("error", error);
    }
}

/* API Acquisition */
const zipCode =  document.getElementById("zip").value;
const userResponse = document.getElementById("feelings").value;
const apiKey = "4c603ee35d9242056474d3fbf69afec3";
const baseURL = `https://api.openweathermap.org/data/2.5/weather?zip=${zipCode},&appid=${apiKey}`;

let d = new Date();
let getDate = d.getDate() + "/" + d.getMonth() + "/" + d.getFullYear();

const getGenerate = document.getElementById("generate");
getGenerate.addEventListener("click", retrieveData);

/* GET request to API */
const getWeatherData = async(baseURL, zipCode, apiKey) => {
    const res = await fetch(baseURL + zipCode + apiKey);
    try {
        const data = await res.json();
        console.log(data)
    }  catch(error) {
        console.log("error", error);
    }
}

/* Adding API & User Data */
function retrieveData(e) {
    getWeatherData(baseURL, zipCode, apiKey)
    .then(function(data) {
        console.log(data);
        postData("/addData", 
        {temp: temp, date: getDate, content: userResponse});
    })
    .then(
        updateUI()
    )
}

/* Updating UI */
const updateUI = async() => {
    const request = await fetch("/all");
    try {
        const allData = await request.json();
        console.log(allData);
        document.getElementById("temp").innerHTML = allData[0].temp;
        document.getElementById("date").innerHTML = allData[0].date;
        document.getElementById("content").innerHTML = allData[0].userInput;
    } catch(error) {
        console.log("error", error);
    }
};

HTML markup:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Weather Journal</title>
  <link href="https://fonts.googleapis.com/css?family=Oswald:400,600,700|Ranga:400,700&display=swap" rel="stylesheet">
  <link rel="stylesheet" href="style.css">
</head>
<body>
  <div id ="app">
    <div class="holder headline">Weather Journal App</div>
    <div class="holder zipcode">
      <label for="zc">Enter Zipcode here</label>
      <input type="text" id="zip" placeholder="enter zip code here">
    </div>
    <div class="holder userresponse">
      <label for="ur">How are you feeling today?</label>
      <textarea class="myInput" id="feelings" placeholder="enter your feelings here" rows="9" cols="50"></textarea>
      <button id="generate" type="submit">Generate</button>
    </div>
    <div class="holder entry">
      <div class="title">Most Recent Entry</div>
      <div id="entryHolder">
        <div id="date"></div> 
        <div id="temp"></div>
        <div id="content"></div>
      </div>
    </div>
  </div>
  <script src="app.js" type="text/javascript"></script>
  <script src="../server.js" type="text/javascript"></script>
</body>
</html>

Answer №1

Key Points:

  1. Your "server side code" should be named server.js
  2. Your "client side code" should be named website/app.js
  3. Your "HTML code" should be named website/index.html

Issue #1 - Lack of response in addData.

No responses for requests to /addData. Consider adding a res.send() or similar, for example

res.json(newEntry); // as the expected response

Issue #2 - Mixing server-side code with client-side HTML.

Remove server.js from your HTML template. Use absolute paths for static assets

<link rel="stylesheet" href="/style.css"> <!-- use "/" -->

<!-- ... -->

<script src="/app.js"></script> <!-- use "/" -->

<!-- remove this line
<script src="../server.js"></script>
-->

Issue #3 - Opening HTML file directly from filesystem.

Start Express server using...

node server.js

and access it via http://localhost:8000/.

Issue #4 - Redundant inclusion of zipCode and apiKey in baseURL.

Avoid appending them to fetch() URL.


Further Enhancements...

  1. Omit the body-parser library. It is outdated; refer to official Express guide instead

  2. Prioritize registering the cors() middleware. Errors in other middleware can disrupt CORS integrations, affecting response reception

    app.use(cors()); // cors first
    
    // built-in body parsing
    app.use(express.json());
    app.use(express.urlencoded());
    

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 best way to open a new window, such as a music player, and integrate it into a Shopify environment

Currently, within my Shopify store, I am using the following code: <script language="javascript" type="text/javascript"> function popupwindow(url, winName, w, h) { var left = (screen.width/2)-(w/2); var top = (screen.height/2)-(h/2); return wi ...

JavaScript code that retrieves an array containing only the deleted images from the information obtained from the edit product page

Currently, I am working on an edit product page in react with a node backend. The situation is as follows: Initially, the product had 4 images (a.png, b.png, c.png, d.png). I have made updates by removing the a.png image and adding a new image e.png. So ...

Is it possible that using npm link could be the root cause of the "module not

As I delve into understanding how to utilize TypeScript modules in plain JavaScript projects, it appears that I am facing a limitation when it comes to using npm linked modules. Specifically, I can successfully use a module that is npm-linked, such as &apo ...

Hybrid component that combines static and dynamic elements in Gatsby

The inconsistency in behavior between the site generated by gatsby develop and gatsby build is causing an issue where the site works during development but not when it's in production. An overview of my website: My website is a simple blog-like plat ...

Utilizing nodejs and mongodb for dual login functionality

Is it possible to implement a login system with two different roles: administrator and user? I want each role to be redirected to their own respective page upon logging in. Can anyone provide guidance or suggestions on how to achieve this? Below is my mod ...

Modifying element size using jQuery causes issues with maintaining a 100% height

I am facing an issue with a sidebar that is styled using the following css properties: background:#164272; position:absolute; left:0px; top:70px; width:250px; height:100%; When I use jQuery to display a table that is initially hidden and on ...

Having issues with AJAX and .change() function not functioning correctly?

I am working on two drop-down menus. The first menu displays the provinces in the country, and when a province is selected, the second menu should show the districts within that province. The following code is for displaying the provinces: $(document).re ...

Enhance the connectivity of Angular js by activating the link function post transclusion

I am facing an issue with Angular where I have two directives that need to be transcluded within each other. However, I am unable to access the DOM using a simple JQuery selector after the transclude function has been executed. Specifically, I need to comp ...

When the user clicks, the template data should be displayed on the current page

I need help with rendering data from a template on the same HTML page. I want to hide the data when the back button is clicked and show it when the view button is clicked. Here is my code: <h2>Saved Deals</h2> <p>This includes deals wh ...

Utilize an Ajax dropdown menu that allows users to enter search criteria, such as location or city

Looking for a way to display weather information based on a selected city? Check out this code snippet that uses Yahoo API to pull data and show weather details. Here's the code: <HTML> <HEAD> <TITLE>Find Weather in major cities ar ...

How can I display an ngx spinner after a delay of 1 second?

I am uncertain about the answer I came across on this platform. intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> { const time = 900; const spinnerLogic = () => { if (this.isRequestServed ...

The issue with displaying inline block is that the divs are not appearing side by side on the

Two of my div elements, namely form-panel and data-panel, are currently not aligned on the same line. How can I use display:inline-block to align them in a single line? Please review the code provided below. I have already used display:inline-block on both ...

Determine whether a WebElement contains a particular content within the :after pseudo class

After locating my element in Selenium, I've come across an interesting challenge. IWebElement icon = box.FindElement(By.ClassName("box-icon")); Sometimes, this element (icon) has a content set as follows: &:after { content: $icon-specia ...

JavaScript: Passing the "this" object in an AJAX request situation

Here is the code snippet I am working with: $(function(){ $("#CASA").click(function(){ rsExecute("rs/rs_luci.php","premi",1,function(cc){}); var col=$( this ).css( "background-color" ); se ...

What sets apart window.location.href from this.router.url?

I'm curious about the various methods of obtaining the current URL in Angular. For instance: this.router.url My main question is: What advantages does using this.router.url offer over simply using window.location? Could someone kindly provide an exp ...

jQuery is missing an essential component that is causing an error

I have successfully implemented the following JavaScript code and everything is working fine. However, I'm uncertain if my code is fully correct. I noticed that in my script, I only utilize success: function() without incorporating an error function. ...

Node.js encountered an error: TypeError - req.end does not have a function

Encountering an error stating that req.end is not a function, even though it works elsewhere in the code. Upon researching, some sources suggest that the global req variable might have been misplaced or lost. However, I haven't used any other variabl ...

The getSession provided by the getSession function is accessible within getServerSideProps but appears as undefined within the component

Whenever I try to log the session variable inside the Dashboard component, it comes back as undefined. However, when I log it inside the getServerSideProps function, it returns the correct details. Am I missing something here? Objective: My goal is to fet ...

Using Jquery to toggle the visibility of a DIV element and adding a blinking effect when it becomes visible

I have a hidden div that is displayed when a link is clicked, and I want it to blink as well. Here is my current setup: The link to display the hidden div: <a class="buttons" href="#" onclick="show(this)">join us</a> The hidden div to be di ...

What could be causing my input to not activate my function?

I am having issues with my input buttons not triggering my functions. Can anyone provide some insight into this problem? <div id="windowBar"> <h3>Imagine you were a superhero...</h3> <input id="WindowClose" type="button" onclick=" ...