Response Processing - SyntaxError: Unexpected end of input when using mode: 'no-cors'

I tried calling ReactJS fetch for REST-API and want to process the response. The call works, I get the answer that I 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) }); } 

When I try to process the response, I got "SyntaxError: Unexpected end of input" in

 return response.json(); 

The .log console looks like this:

Console.log (response)

My JSON answer looks like this, it really is, I tested 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" } } ] 
+16
source share
5 answers

You need to remove the mode: 'no-cors' from your request. This mode: 'no-cors' is exactly the reason for the problem you are facing.

mode: 'no-cors' request mode: 'no-cors' makes the response type opaque . The console log snippet in question clearly shows this. And opaque means your JavaScript code cannot see the response body or headers.

https://developer.mozilla.org/en-US/docs/Web/API/Request/mode explains:

no-cors - JavaScript may not have access to any properties of the resulting Response

Therefore, the effect of setting mode: 'no-cors' essentially tells browsers: "Do not allow external JavaScript to access the body or headers of the response under any circumstances."

I assume that you set mode: 'no-cors' for the request because the response from http://localhost:8080/course does not include the Access-Control-Allow-Origin response header or because your browsers make an OPTIONS request for http://localhost:8080 because your request calls a preliminary CORS check .

But setting mode: 'no-cors' not a solution to these problems. The solution is either:

+35
source

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

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

If you want to receive an 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(); }) 
+2
source

I know this answer may be too late and could be resolved, but I had the same problem today, and I just needed to add ',' at the end of the header hash, and I stopped getting the error

 export function addContacts(formData) { return(dispatch) => { dispatch({type: 'POSTING_CONTACTS'}); console.log(formData) return fetch(uri, { method: 'POST', body: JSON.stringify({contact: {name: formData.name, phone_number: formData.phoneNumber}}), headers: { Accept: 'application/json', 'Content-Type': 'application/json' }, }) .then(response => { return response.json() }).then(responseJSON => { console.log(responseJSON) return dispatch({type: 'ADD_CONTACT', payload: responseJSON}); }) } } 
+1
source

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

 <?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 the working sample code with the POST request:

 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; }); 
0
source

Just copy the following code and paste it into the web.config file under <system.webServer> .

 <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> 
0
source

Source: https://habr.com/ru/post/1266540/


All Articles