handle response - syntaxerror: unexpected end of input when using mode: 'no-cors'

  • Last Update :
  • Techknowledgy :

So the effect of setting no-cors mode is essentially to tell browsers, “Don’t let frontend JavaScript code access the response body or headers under any circumstances.” People sometimes try setting no-cors mode when a response doesn’t include the Access-Control-Allow-Origin response header or else because the request is one that triggers a CORS preflight, and so your browser does an OPTIONS preflight. If you want to have the error message in your rejected promise, you can do something like:

In your then you should check if the response is OK before returning response.json:

.then(function(response) {
   if (!response.ok) {
      return Promise.reject('some reason');
   }

   return response.json();

})
2._
.then(function(response) {
   if (!response.ok) {
      return response.text().then(result => Promise.reject(new Error(result)));
   }

   return response.json();
})

Suggestion : 2

Error: SyntaxError: Unexpected end of JSON input when using fetch() Error installing reactjs: Error unexpected end of JSON input while parsing near apollo graphql mutation - Unexpected end of JSON input create-react-app : npm ERR! Unexpected end of JSON input while parsing near '....'

To better understand your error, add a catch case to your fetch request.

Also, if you use arrow functions, you don't need to bind(this);

fetch(feedURL, {
      "mode": "no-cors"
   })
   .then(response => response.json())
   .then(data => {
      this.setState({
         data: data
      });
   })
   .catch(resp => {
      console.error(resp);
   });

Suggestion : 3

A no-cors request makes the response type opaque. The log snippet in the question shows that. Opaque means your frontend JavaScript code can’t see the response body or headers. So the effect of setting no-cors mode is essentially to tell browsers, “Don’t let frontend JavaScript code access the response body or headers under any circumstances.” But using no-cors mode is not the solution to those problems. The solution is either to:

Simply copy the following code and paste it on your web.config file under <system.webServer> tag.

<httpProtocol>
   <customHeaders>
      <add name="Access-Control-Allow-Origin" value="*" />
      <add name="Access-Control-Allow-Headers" value="Content-Type" />
      <add name="Access-Control-Allow-Methods" value="GET, POST, PUT, DELETE, OPTIONS" />
   </customHeaders>
</httpProtocol>

You can avoid the problem with CORS policy by adding in the header of php or another server endpoint the row:

< ? php
header('Access-Control-Allow-Origin: *');
//or
header('Access-Control-Allow-Origin: http://example.com');

// Reading JSON POST using PHP
$json = file_get_contents('php://input');
$jsonObj = json_decode($json);

// Use $jsonObj
print_r($jsonObj - > message);

...
// End php
?
>

Model of working fetch code with POST request is:

const data = {
   optPost: 'myAPI',
   message: 'We make a research of fetch'
};
const endpoint = 'http://example.com/php/phpGetPost.php';

fetch(endpoint, {
      method: 'POST',
      body: JSON.stringify(data)
   })
   .then((resp) => resp.json())
   .then(function(response) {
      console.info('fetch()', response);
      return response;
   });

In your then you should check if the response is OK before returning response.json:

.then(function(response) {
   if (!response.ok) {
      return Promise.reject('some reason');
   }

   return response.json();

})

If you want to have the error message in your rejected promise, you can do something like:

.then(function(response) {
   if (!response.ok) {
      return response.text().then(result => Promise.reject(new Error(result)));
   }

   return response.json();
})

Suggestion : 4

I was getting a similar issue and found that it was happening because I had mode: 'no-cors' set in fetch but cors was set on the server. Worth checking if it happens to anyone else. I was getting a similar issue and found that it was happening because I get the backend response is not JSON format. Worth checking if it happens to anyone else. @steveluscher i'm not sure when this started happening...seems odd though, given that people are constantly using fetch and I don't see that this error has been reported before.

1._
import React, {
  Component,
  Text,
  View,
} from 'react-native';

export default class SampleApp extends Component {
  constructor() {
    super();
    this.state = {
      text: 'Please wait. Loading.',
    };
  }
  componentDidMount() {
    fetch('http://jsonplaceholder.typicode.com/posts/1')
      .done(result =>
        result.text().done(text => this.setState({text}))
      );
  }
  render() {
    return (
      <View style={{margin: 30}}>
        <Text>{text}</Text>
      </View>
    );
  }
}
2._
Summary: This fixes facebook #6326 with updating https://github.com/facebook/react-native/blob/master/Libraries/Fetch/fetch.js to latest from  https://github.com/github/fetch.

cc skevy steveluscher
Closes facebook# 6347

Differential Revision: D3024308

Pulled By: davidaurelio

fb - gh - sync - id: da87827b94d683aeb66be345e255bd771fdba1be
shipit - source - id: da87827b94d683aeb66be345e255bd771fdba1be
3._
const serialized = JSON.stringify(formData)
const opts = {
   method: 'post',
   headers: {
      'Content-type': 'application/json'
   },
   body: serialized
}

Suggestion : 5

configure the http://localhost:8080 server to send the Access-Control-Allow-Origin response header and to handle the OPTIONS request configure the http://localhost:8080 server to send the Access-Control-Allow-Origin response header and to handle the OPTIONS request When i try to handle the response, i got a "SyntaxError: Unexpected end of input" at So the effect of setting no-cors mode is essentially to tell browsers, “Don’t let frontend JavaScript code access the response body or headers under any circumstances.”

I tried a ReactJS fetch call to a REST-API and want to handle the response. The call works, i get a response, which i can see in Chrome Dev Tools:

function getAllCourses() {
   fetch('http://localhost:8080/course', {
      method: 'POST',
      mode: 'no-cors',
      credentials: 'same-origin',
      headers: {
         'Accept': 'application/json',
         'Content-Type': 'application/json',
      },
      body: JSON.stringify({
         objectClass: 'course',
         crud: '2'
      })
   }).then(function(response) {
      console.log(response);
      return response.json();

   }).catch(function(err) {
      console.log(err)
   });
}
2._
return response.json();

My Response JSON looks like this, it is valid, i checked it with jsonlint:

[{
   "0x1": {
      "users": [],
      "lectures": [],
      "owner": "0x2",
      "title": "WWI 14 SEA",
      "description": null,
      "objectClass": "course",
      "id": "course_00001"
   },
   "0x2": {
      "username": "system",
      "lectures": [],
      "course": null,
      "solutions": [],
      "exercises": [],
      "roles": [
         "0x3",
         "0x4",
         "0x5"
      ],
      "objectClass": "user",
      "id": "user_00001"
   },
   "0x3": {
      "roleName": "ROLE_ADMIN",
      "objectClass": "role",
      "id": "role_00001"
   },
   "0x4": {
      "roleName": "ROLE_STUDENT",
      "objectClass": "role",
      "id": "role_00002"
   },
   "0x5": {
      "roleName": "ROLE_DOCENT",
      "objectClass": "role",
      "id": "role_00003"
   }
}]

Suggestion : 6

I'm using React and trying to send a simple fetch in a project that is frontend-only. I was getting a CORS error, so I added mode: "no-cors" to the fetch, following the advice I found on another StackOverflow question. This resolves the CORS error, but now I'm getting an 'SyntaxError: Unexpected end of input' error. None of the data is being saved to state, so the fetch is not being completed properly. I don't have access to edit the JSON file, but I can't do anything for this exercise without being able to fetch the data. CORS is something you need to set on the backend. If it isn't configured, you can't access that endpoint directly from the frontend. You'll have to use a proxy to forward the request for you "no-cors" isn't magically going to make the CORS error disappear

Here's what I have in my App.js:

import React, { Component } from "react";
import {
  BrowserRouter as Router,
    Switch,
    Route,
    Link,
    withRouter
  } from "react-router-dom";
  import ContactList from "./components/ContactList";

  class App extends Component {
    constructor() {
      super();

      this.state = {
        contacts: []
      };
    }

    componentDidMount() {
      this.fetchContacts();
    }

    fetchContacts = () => {
      fetch("https://s3.amazonaws.com/technical-challenge/v3/contacts.json", {
        mode: "no-cors"
      })
        .then(resp => resp.json())
        .then(contacts => {
          this.setState({
            contacts: contacts
          });
        })
        .catch(alert);
    };

    render() {
      return (
        <div>
          {this.state.contacts.map(contact => {
            return <p>{contact.name}</p>;
          })}
          <ContactList contacts={this.state.contacts} />
        </div>
      );
    }
  }

  export default withRouter(App);

Suggestion : 7

Doing a curl works but with fetch no chance, does anyone see the issue here? I allowed my current IP Address and I do the fetch from localhost:3000 As the message suggests to add ‘no-cors’ I also tried this but then I get this Powered by Discourse, best viewed with JavaScript enabled This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.

Hello, I try to use the Realm Administration API and this is the function for getting the token.

async function cloudLogin() {
    const response = await fetch(
      "https://realm.mongodb.com/api/admin/v3.0/auth/providers/mongodb-cloud/login",
      {
        method: "POST",
        headers: {
          "Access-Control-Allow-Origin": "*",
          "Content-Type": "application/json",
        },
        body: JSON.stringify({
          username: "<Public API Key>",
          apiKey: "<Private API Key>",
        }),
      }
    );
    const json = await response.json();
    console.log(json);
  }

The error I get is

Access to fetch at 'https://realm.mongodb.com/api/admin/v3.0/auth/providers/mongodb-cloud/login'
from origin 'http://localhost:3000'
has been blocked by CORS policy: Response to preflight request doesn 't pass access control check: No '
Access - Control - Allow - Origin ' header is present on the requested resource. If an opaque response serves your needs, set the request'
s mode to 'no-cors'
to fetch the resource with CORS disabled.
3._
Uncaught( in promise) SyntaxError: Unexpected end of input
this line >
   const json = await response.json();