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

Jesse Thompson
Jesse Thompson
10,684 Points

fetch() doesnt work on nested address

I have this react function that works on my main domain http://localhost:3000/ But when I run the method on http://localhost:3000/watch/ it gives me this

"App.js:604 POST http://localhost:3000/watch/users/searchusers 404 (Not Found)" "SyntaxError: Unexpected token < in JSON at position 0 at App.js:617"

Seems the express app will only allow this to work at the main domain. How can I change this without redirecting on my /watch/ page?

// react method
fetchusers(e) {
        let searchusers = document.getElementById('usersearch').value;
        if (searchusers) {
            fetch('users/searchusers', {
                method: "POST",
                headers: {
                    'Accept': 'application/json',
                    'Content-Type': 'application/json'
                },
                credentials: 'same-origin',
                body: JSON.stringify({
                    searchusers
                })
            })
            .then(function(response) {
                // You parse the data into a useable format using `.json()`
                return response.json();
            })
            .then(function(data) {
                // `data` is the parsed version of the JSON returned from the above endpoint.
                console.log(data);  // { "userId": 1, "id": 1, "title": "...", "body": "..." }
            })
            .catch(error => { console.log(error);});
        }
        e.preventDefault();
    }

// express route
router.post('/searchusers', (req, res, next) => {
    console.log(req.body.searchusers);
    if (!req.body.searchusers) {
        res.json({querystatus: 'empty friend search query'});
    } else {
        // the following makes a query to the database for users matching the user search input and only returns the username and id.
        User.find({username: new RegExp(req.body.searchusers) }, {username: 1} , function(err, result) {
            if (err) throw err;
            console.log(result + ' these are results')
            res.json(result);
        });
    }
});

2 Answers

Emma Willmann
seal-mask
.a{fill-rule:evenodd;}techdegree seal-36
Emma Willmann
Treehouse Project Reviewer

My first thought I agree with what Adam Beer said. With your current url wrapped in quotes, the fetch is looking for that exact wording (users/searchusers) in the path . If that should actually be 'users/' with a user id after the slash, then you should use a template literal. Wrap the url in back ticks and then the searchusers inside curly braces with a $ in front of it. If searchusers === 123, then the url it fetches would be 'users/123'.

Jesse Thompson
Jesse Thompson
10,684 Points

Not sure if you meant typing this: fetch(users/${searchusers} , {

I think you misunderstood what I meant, no big deal but it wasnt an issue of appending the json info the address, its a put request. it was that it was making a request for http://localhost:3000/watch/users/searchusers since I was on page http://localhost:3000/watch/ but I needed http://localhost:3000/users/searchusers.

But I ended up to putting the dev and production environments into a variable and switching as needed.

fetch(currentrooturl + 'users/searchusers',

Adam Beer
Adam Beer
11,314 Points

Just a tip, but what happend if you modify this section

fetch('users/searchusers',

to

fetch(`users/${searchusers}`,