Attempting to retrieve data from an object by utilizing an external URL, however

Upon starting the bot console, the console displays:

Online with undefined/5

After 10 seconds, an error is thrown:

undefined:1 [object Promise] ^ SyntaxError: Unexpected token o in JSON at position 1

This is the code snippet being used:

let players
client.on("ready", async () => {

async function fetchOnlinePlayers() {
    const response = fetch(`http://ip:port/dynamic.json`);
    const data = JSON.parse(response);
    players = data.clients;
}

async function autoconnect() {
    if (players === -1) {
        console.log('Offline');
    } else {
        console.log('Online with ' + players + '/5');
    }
}

autoconnect()

setInterval(() => {
    client.user.setStatus('dnd');
    client.user.setActivity(`Online with ${players} players.`, { type: 'PLAYING' })
    fetchOnlinePlayers()
}, 10000)

})

Answer №1

Your code has several issues that need to be addressed. Here is a breakdown of the required fixes:

Necessary corrections

  • It is crucial to utilize await to receive the actual response, as mentioned by @about14sheep.
  • Instead of using JSON.parse() on a response, you should use response.json() to access the JSON body.
  • Choosing the correct operator is essential; for numbers, it is recommended to use == instead of ===.
  • If you encounter 'undefined' before 10 seconds have elapsed, ensure to call the function prior to the setInterval() function.

Additional enhancements I implemented

  • Improved the formatting of the JavaScript code
  • Added semicolons where required
  • Leveraged the ES6 template literals feature
  • Eliminated unnecessary async declarations

The following code snippet addresses and resolves all of these issues.

let players;

client.on('ready', async () => {

    async function getOnlinePlayers() {
        const response = await fetch(`http://ip:port/dynamic.json`);
        const data = await response.json();
        players = data.clients;
    }

    function autoconnect() {
        if (players == -1) {
            console.log('Offline');
        } else {
            console.log(`Online with ${players}/5`);
        }
    }

    autoconnect();
    getOnlinePlayers();

    setInterval(() => {
        client.user.setStatus('dnd');
        client.user.setActivity(`Online with ${players} players.`, {
            type: 'PLAYING'
        });
    }, 10000);

});

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

"Troubleshooting: Why is my JSON feed returning null with jQuery getJSON

There seems to be an issue with the data being returned as null. Unfortunately, I do not have direct access to resolve this problem. A server admin will need to update the feed according to my requirements. If you know of a solution that does not involve m ...

Logging out of Laravel after sending a POST request

I'm developing a laravel application that heavily relies on POST requests. One common type of request in my app looks like this: var classElements = document.querySelectorAll("tr.ui-selected td.filename"); var csrf = $('input[name=_token]') ...

Tips for creating a unique custom UI headline using ReactJS, CSS, and bootstrap

Looking to create a design that is responsive in ReactJS using Bootstrap or CSS if needed. I need assistance with placing separators between columns and ensuring the values of each label are aligned in the same column but on the next line. The layout shoul ...

Unstyled Cards Failing to Receive Design

I am currently working on creating a prototype that utilizes two Bootstrap 4 cards to display information from a form and store related information from another form in the second card. The current layout of this setup can be observed below: https://i.sst ...

Tips for choosing and emphasizing specific lines in a dxf document with the help of three.js, dxf-parser, and three-dxf

Incorporating both the dxf-parser and three-dxf libraries, I am working on a webpage to display dxf drawings with the help of the three.js library. Although I was successful in loading the dxf file onto the webpage, I encountered difficulties in highligh ...

Modifying the information depending on the option chosen from the dropdown menu using angularJS

I have a dropdown menu where I can choose between two options, and when selected, the corresponding data is displayed. However, I would like to display the data that is inside a div tag instead. Check out this Fiddle Demo HTML: <div ng-controller="Ct ...

Convert text into a clickable link

Creating a form with numerous text fields, some of which require numerical input. The main goal is to have users enter a tracking number, order number, or any other type of number that, when submitted, will open a new URL in a separate window with the spec ...

What varieties of ajax styles are there?

Although I am still relatively new to utilizing ajax, I have found a lot of success in my endeavors so far. The majority of my ajax calls tend to follow this format: function saveQueryProf(){ var currentDate = new Date(); var date=currentDate. ...

Ways to change the URL post saving a cookie with express?

I have written this code for user login in my Express router: if (password === realpassword) { res.cookie('thecookie', 'somethingliketoken'); res.redirect(302, '/somepages'); } else { res.status(403).end(); } The ...

Errors occur when using jQuery Autocomplete alongside Angular HTTP

I have implemented an ajax autocomplete feature for my database using the jQuery-Autocomplete plugin. Below is my current code setup: HTML: <input ng-keyup="searchCustomer()" id="customerAutocomplete" type="text"> Angular $scope.searchCustome ...

Guide on creating Jasmine tests for $resource in AngularJS

Trying to get started with defining tests for my angular app, but feeling a bit lost as it's my first time working with testing. I'm specifically interested in setting up Tests with Jasmine for REST Services within my application. My main questi ...

What might be causing the in-viewport javascript to not work in my code?

Why is my in-viewport JavaScript code not functioning properly? Link to JSFiddle code When the Click to move button is clicked, the cat image will slide correctly. However, when implementing the following code: if($("#testtest").is(":in-viewport")) ...

Experiencing issues with creating HTML using JavaScript?

I'm a JavaScript novice and struggling to figure out what's wrong with my code. Here is the snippet: var postCount = 0; function generatePost(title, time, text) { var div = document.createElement("div"); div.className = "content"; d ...

The replication technique in Threejs

I am experiencing an issue while attempting to clone some Vector3 objects, as the copied clones are created with all zero values in x, y, and z. Here is an example: When I use this statement console.log(this.geometries[j].vertices[i].multiplyScalar(1)); ...

I'm looking to add autocomplete functionality to a text input in my project, and then retrieve and display data from a MySQL database using

Looking to enhance user experience on my form where users can select inputs. Specifically, I want to implement a feature where as the user starts typing in a text input field with data from a MYSQL database, suggestions will be displayed. The form is locat ...

Transform a delimited string into a hierarchical JSON format using Python

Is there a way to convert delimited strings into hierarchical JSON using Python? (I came across a solution for a similar issue in jQuery but now I need help finding a solution specifically for Python.) The aim is to create a JSON structure of categories f ...

Tips for transferring data from a pop-up or modal window to the main window in ASP.NET MVC

Currently, I am in the process of developing a contact form within ASP.NET MVC. This contact form will allow users to easily attach regular files through traditional file and browse functions. Additionally, users will have the option to search for a specif ...

Changing links dynamically through jQuery

Below is the dynamicpage.js script: $(function() { var newHash = "", $mainContent = $("#main-content"), $pageWrap = $("#page-wrap"), baseHeight = 0, $el; $pageWrap.height($pageWrap.height()); ba ...

"Encountering a 'Cannot GET' error message while utilizing Rest API in Node.js

Currently, I am developing a project using nodejs along with the expressjs framework. My focus right now is on setting up and running a "Rest Api," but I seem to be encountering an error message that reads: Cannot GET /published Let me share my routes fil ...

Adding JSON data obtained from an API into a database

This is my first time seeking help on this platform, hoping someone can assist me with a programming issue. I am relatively new to PHP and currently working on a program to fetch data from an external booking system and store it in my database. I have wri ...