简体   繁体   中英

Why is fetch returning my React app's index.html instead of the URL I provided?

I'm trying to make a fetch request in JavaScript. The goal is to get all the JSON from here into my React app. I think I'm using one of the simplest methods available, but I'm still managing to mess up..

My expected result is a console.log() output with the json data. The result I'm getting instead is an error that says

Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 0

In my exploration of the problem, I changed some of my code that says .then(results => results.json()) to .then(results => results.text()) . That shows me the text of whatever my fetch request is getting. I discovered it's not getting to the supplied URL at all, but instead is returning my app's homepage (index.html, located at "/", I think). Weird.

Here is the abridged version of my code:

import React from "react";

const hardcoded_url =
    "https://www.reddit.com/r/learnprogramming/new/.json?count=25&after=";

getJSON = () => {
        fetch(this.hardcoded_url)
            .then(results => results.json())
            .then(data => console.log(data));
    };

render() {
    return (
        // <react stuff>
    )
}

What my console.log(data) prints out is literally the index.html of my React app:

<!DOCTYPE html>
<html lang="en">
<!--- blah blah --->
</html>

I can even see the request go off in my Developer Tools network tab. To me, it doesn't look right. It registers as undefined and under Network -> Headers -> General :

Request URL: http://localhost:3000/undefined
Request Method: GET
Status Code: 304 Not Modified

I've tried Googling the error messages and javascript fetch url returns index.html . The latter lead me to this page which looked promising, but adding the "proxy" line to my package.json didn't help (Specifically, I added: "proxy": "http://localhost:3000" ). I also don't think it's a credentials problem because I can access the URL I'm after just from my browser.

I don't understand why this isn't working out for me. I'm copying the form of code from somebody else's github project for my own little Reddit clone. Theirs works...

hardcoded_url is a const and not the class variable. Accessing it by this.hardcoded_url is the issue.

fetch(hardcoded_url) is the correct way here.

this.hardcoded_url is undefined and so fetch is having undefined as the url considered relative the localhost and so API is http://localhost:3000/undefined instead of the actual url

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM