React Js : Text response is empty when using fetch

 Today i faced the below issue when learning react Js , Im documenting it here so that it will help people like me.

I was trying to do a Rest APi request to backend server using fetch like below :


fetch(url,{
method: 'GET',
mode: 'no-cors'
})
.then((res) => {
return res.text();
})
.then((data) => {
                console.log(data);
setIsAuth(data);
})
.catch((error) => console.error("Error:",error));

When i execute it backend server was returning a valid response but on the cosole it was displaying blank.

Upon research i found that :

i have to Remove mode: 'no-cors'.

When you use no-cors mode, you’re explicitly specifying that you want an “opaque response”.

Your script can’t access any properties of an opaque response—instead essentially all you can do is cache it. no-cors mode is basically useful only when doing caching with Service Workers.

If the reason you have your script using no-cors mode is because cross-origin requests to the server otherwise won’t work, the right solution is either to update the server-side code to send the Access-Control-Allow-Origin response header and other CORS headers—if you have access to the server do to that—or else, use a proxy like https://cors-anywhere.herokuapp.com/.

Comments

Popular posts from this blog

Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed: java.lang.NoSuchMethodError: 'boolean org.springframework.web.context.request.async.WebAsyncManager.isMultipartRequestParsed()'] with root cause java.lang.NoSuchMethodError: 'boolean org.springframework.web.context.request.async.WebAsyncManager.isMultipartRequestParsed()'

JPA Connect to multiple datasources