Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

Andrew Cauthorn
Andrew Cauthorn
6,967 Points

Why do I keep getting an "is not valid JSON" message

I keep getting an error in my console that says "Unexpected token '<', "<html><bod"... is not valid JSON" and I have no idea why. My code ran perfectly fine yesterday. Any thoughts on what the issue could be?

const https = require("https");
const http = require("http");

// Print the data
function printMessage(username, badgeCount, points) {
    const message = `${username} has ${badgeCount} total badge(s) and ${points} points in JavaScript`;
    console.log(message);
}
function printError(error) {
    console.error(error.message);
}

function getProfile(username) {
    // Connect to the API URL (https://teamtreehouse.com/csalgado.json)
    const request = https.get(
        `https://teamtreehouse.com/${username}.json`,
        (response) => {
            let body = "";
            // Read the data
            response.on("data", (data) => {
                body += data.toString();
            });
            response.on("end", () => {
                try {
                    // Parse the data
                    let profile = JSON.parse(body);

                    printMessage(
                        username,
                        profile.badges.length,
                        profile.points.JavaScript
                    );
                } catch (error) {
                    printError(error);
                }
            });
        }
    );
    request.on("error", (error) => printError(error));
}
const users = process.argv.slice(2);
users.forEach(getProfile);

2 Answers

Rachel Johnson
STAFF
Rachel Johnson
Treehouse Teacher

Hey Andrew Cauthorn ! Thanks for posting.

While I'm not 100% sure about the context of this question, I can say that the API is not https://teamtreehouse.com/USERNAME.json but https://teamtreehouse.com/profiles/USERNAME.json

You're likely getting the error because what's being returned is the redirect, which isn't JSON (hence the error).

If you can share what video/course is got you to use the https://teamtreehouse.com/USERNAME.json URL, we can make sure it gets amended!

Andrew Cauthorn
Andrew Cauthorn
6,967 Points

Thank you, Rachel Johnson! And my apologies for the late reply. The course I'm taking is node.js basics. I believe there are a few videos that reference the incorrect URL.