5

I've been trying to make an React site, which would fetch a GET-response from API and print it out to my .html-file. I've managed to fetch the file just right, but i can't access the JSON-data server sends me.

If i use no-cors in my Fetch-request, i get an opaque response containing pretty much nothing, but if i go to Developer tools i can find my data there and read it. If i do use cors, almost same thing. I get an 403-error, but my data is in the browser memory, but my code doesn't print it out. I can find the response from Network in developer tools.

Why does the server give me an error, but still i get my data? And how can i access it, if it's in the browser?

class Clock extends React.Component {
    constructor(props) {
        super(props)
          this.state = {data2: []}
          this.apihaku = this.apihaku.bind(this)
     }

     componentDidMount() {
         this.apihaku(),
         console.log("Hei")
     }

     apihaku () {
         fetch('https://#######/mapi/profile/',
         {method: 'GET', mode:'no-cors', credentials: 'include',
         headers: {Accept: 'application/json'}}
         ).then((response) => {
              console.log(response);
              response.json().then((data) =>{
              console.log(data);
         });
    });
}

render() {
    return <div>
        <button>Button</button>
    </div>
}}

ReactDOM.render(
   <Clock />,
       document.getElementById('content')
)

EDIT: Error images after trying out suggestions

https://i.sstatic.net/wp693.png

https://i.sstatic.net/07rSG.png

https://i.sstatic.net/XwZsR.png

6
  • can you put this.apihaku() in componentDidMount() and see Commented Mar 11, 2018 at 12:14
  • Same errors, it keep giving for this sentence: "response.json().then(data => { console.log("Heih2");" The error message is: Uncaught (in promise) SyntaxError: Unexpected end of input. I can still see the data in console. Commented Mar 11, 2018 at 12:40
  • "Why does the server give me an error, but still i get my data?" - how could we possibly know that ...? Do you think we have the documentation for https://#######/mapi/profile/ open here in front of us, because you made it so easy for us to figure out what API you are actually talking about here? "And how can i access it, if it's in the browser?" - by fixing whatever you are doing wrong in talking to this mystery API in the first place, so that it doesn't respond with a status code that signals to the browser "something went wrong, discard the response body" any more. Commented Mar 11, 2018 at 12:49
  • Sorry about that, but i'm not really sure what kind of info should i provide. I'm not sure are the error messages enough with code or not. The API is for a work project, so i can't really reveal the address. The opaque response that i get from server comes with code 0, but when i go to sources, there is an response 200 OK, where the data is. I'll add some pictures to clarify. Commented Mar 11, 2018 at 12:56
  • 1
    Start by removing mode:'no-cors'. When you use mode: 'no-cors' you’re explicitly specifying that you want the browser to block your frontend code from accessing any data in the response body or headers. See the answers at stackoverflow.com/questions/43317967/… and stackoverflow.com/questions/42254685/… Commented Mar 11, 2018 at 22:17

4 Answers 4

5

You're getting an opaque response, because you're using fetch with mode: 'no-cors'. You need to use mode: 'cors' and the server needs to send the required CORS headers in order to access the response.

Sign up to request clarification or add additional context in comments.

Comments

2

Fetch is doing exactly what the documentation says it's supposed to do, from Mozilla:

The fetch specification differs from jQuery.ajax() in two main ways:

The Promise returned from fetch() won’t reject on HTTP error status even if the response is an HTTP 404 or 500. Instead, it will resolve normally (with ok status set to false), and it will only reject on network failure or if anything prevented the request from completing.

By default, fetch won't send or receive any cookies from the server, resulting in unauthenticated requests if the site relies on maintaining a user session (to send cookies, the credentials init option must be set). Since Aug 25, 2017. The spec changed the default credentials policy to same-origin. Firefox changed since 61.0b13.

So you need to use CORS, otherwise you get an opaque response (no JSON), and then 403 to me suggests that you haven't authenticated properly. Test your API with Postman, if I had to take a guess I'd say the API isn't sending the cookie because it's a GET request, so no matter how well you set your headers on the client it won't work. Try it as a POST instead. GET requests should really only be used to drop the initial HTML in the browser. I think for your headers use these, include the creds that the API sends and allow the domain to be different.

mode: "cors", // no-cors, cors, *same-origin *=default
credentials: "include", // *same-origin

Comments

0

Try this and see where is the error happening i believe in the parsing but lets check and see

fetch(https://#######/mapi/profile/, {
    method: "GET",
    headers: {
       "Content-Type": "application/json"
    },
    credentials: "include"
 })
 .then((response) => {
     console.log(response);
     try {
         JSON.parse(response)
     }
     catch(err){
         console.log("parsing err ",err)
     }
})
.catch((err)=>{
    console.log("err ",err)
});

10 Comments

It's still in the same error, does that mean the response is empty? Here are two photos. imgur.com/a/8lWUN & imgur.com/a/C2ynV
can you do JSON.parse(response) instead of response.json() and console log it
Yes, now it jumps to this. Apparently it's already parsed? parsing err SyntaxError: Unexpected token o in JSON at position 1 at JSON.parse (<anonymous>) at fetch.then.response (mainfile.js:17) at <anonymous>
so is your problem solved now , i have updated my answer if anyone else is facing same thing
Actually no, it keeps giving me the same (Unexpected token) error. I'm googling at the same time and if i change it to JSON.stringify, i'll get a response. It's just the Status code 0-response and the 200 OK-response with my JSON is only in browser page like in picture 2 on the original post.
|
0

I had a similar issue, this kind of problem happend when a HTTP port try to send request to a HTTPS endpoint, adding a "mode:'no-cors'" doesn't do what is SOUND doing but rathere when the documentation says.

I fixed the issue by allowing in my API Application for calls from my HTTP port (i'm using a .net 6 as an API in debugging mode, my code look like this https://stackoverflow.com/a/31942128/9570006)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.