Fetch request infinite pending in a new tab in Chrome - reactjs

In my react project Chrome will never send fetch requests if I open a link in a new tab:
chrome network tab
chrome console tab
Here is standard fetch:
let h = new Headers();
h.append('Accept', 'application/json');
h.append('Content-Type', 'application/json');
h.append('X-Custom-Header', '123');
let req = new Request(url, {
method: 'GET',
headers: h, //заголовки
mode: 'cors'
});
fetch(req).then((response) => {
if(!response.ok) {
console.log(response);
}
return response;
})
.then((response) => response.json())
.then((items) => console.log(items.data))
I tried to do this in dev console:
async function load() {
let response = await fetch('/somesite.com', {
method: 'GET',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
'X-Custom-Header': '123'
},
mode: 'cors'
});
let data = await response.json();
console.log(data);
}
load();
XHR requests doesn't work too. Console log is clean, no mistakes. In Mozilla/Opera/Safari everything is fine.
With disabled chrome://flags/#out-of-blink-cors Chrome will send requests correctly. But it doesn't solve issue for all users.
Access-Control-Allow-Origin set correctly.
I don't understand what is wrong...
Useful links:
https://support.google.com/chrome/thread/11089651?hl=en
https://www.chromestatus.com/feature/5768642492891136
https://www.chromium.org/Home/loading/oor-cors

Related

React Remix not sending cookies to remote server

I am trying to set up authentication with Remix as my pure frontend and a django backend.
When the user signs in successfully, the backend sends a cookie with the response and this is set in the browser redirect with remix
const signIn = async (credentials: LoginCreds) => {
try {
const response = await fetch(generateFullBackendUrl('/auth/signin'), {
method: 'POST',
body: JSON.stringify(credentials),
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json'
},
credentials: 'include'
});
return response;
} catch (e) {
console.log(e);
}
}
const response = await authService.signIn({
email,
password
})
const cookies = response?.headers.get('set-cookie');
if(cookies){
return redirect('profile', {
headers: {
'Set-Cookie': cookies
}
});
However when I try to make subsequent fetch calls in my loader the cookies are not sent to the backend as I would expect the browser would
await fetch(generateFullBackendUrl('api/users/me'), {
method: 'GET',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
credentials: 'include'
})
Front end is running on port 3000
Backend running on port 4000
Im wondering why the fetch request in the loader does not send the cookies with the request
You need to read the cookie header from the loader request and pass it to your fetch headers.
There’s no way Fetch can automatically know what headers to send when used server side.
There is a quick workaround but not so elegant solution:
in your loader use this:
export const loader: LoaderFunction = async({request}) => {
const response = await fetch(`/api/books?${new URLSearchParams({
limit: '10',
page: '1',
})}`, {
headers: {
'Cookie': request.headers.get('Cookie') || ''
}
});
console.log(response)
if(response.ok) return await response.json();
}

Fetching an API in react

I am new to React, And I am Stuck. I am trying to make a signup page, having textboxes: name,phonumber,email,password.
What I want is, When I click on login button, all these details should be sent over POST to my API, and response is fetched and stored.
API:
http://localhost:5000/api/users/signup
Method:
POST
Request to my api is send in this way:
content-type: application/json
{
"name": "Devanshh Shrivastvaaaa",
"phoneNumber":"982964XXX8",
"email": "devannnnnshh;#ccc.in",
"password": "1234566788"
}
Can anyone please explain me using code how to send this data to my api on clicking signup, and fetching response
Don't need to use any third party libraries, just use the Javascript fetch API
// Example POST method implementation:
async function postData(url = '', data = {}) {
// Default options are marked with *
const response = await fetch(url, {
method: 'POST', // *GET, POST, PUT, DELETE, etc.
mode: 'cors', // no-cors, *cors, same-origin
cache: 'no-cache', // *default, no-cache, reload, force-cache, only-if-cached
credentials: 'same-origin', // include, *same-origin, omit
headers: {
'Content-Type': 'application/json'
// 'Content-Type': 'application/x-www-form-urlencoded',
},
redirect: 'follow', // manual, *follow, error
referrerPolicy: 'no-referrer', // no-referrer, *no-referrer-when-downgrade, origin, origin-when-cross-origin, same-origin, strict-origin, strict-origin-when-cross-origin, unsafe-url
body: JSON.stringify(data) // body data type must match "Content-Type" header
});
return response.json(); // parses JSON response into native JavaScript objects
}
postData('https://example.com/answer', { answer: 42 })
.then(data => {
console.log(data); // JSON data parsed by `data.json()` call
});
Source: Mozilla MDN
you need to install axios or fetch axios is good axios
axios.post('http://localhost:5000/api/users/signup', {
name: "Devanshh Shrivastvaaaa",
phoneNumber":"982964XXX8",
email: "devannnnnshh;#ccc.in",
password: "1234566788"
})
.then((response) => {
console.log(response);
}, (error) => {
console.log(error);
});
also check for further

How to resolve "Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource" [duplicate]

This question already has an answer here:
Calling Yelp API from frontend JavaScript code running in a browser
(1 answer)
Closed 2 years ago.
I am trying to make a fetch request for my React app, but I keep getting this CORS error. The request works fine in Postman. I have added the Access-Control-Allow-Origin header. I also tried adding mode: 'no-cors', but that did not work either. I can't find anything online for any other solutions. This is the code I'm using:
var myHeaders = new Headers();
myHeaders.append("Authorization", "Bearer <MY_API_KEY>");
myHeaders.append("Cookie", "__cfduid=db290300ecfe95ec1fe3bc92c388c3c991586618117");
myHeaders.append("Access-Control-Allow-Origin", "*");
var requestOptions = {
method: 'GET',
headers: myHeaders,
redirect: 'follow'
};
fetch("https://api.yelp.com/v3/businesses/search?location=Houston", requestOptions)
.then(response => response.text())
.then(result => console.log(result))
.catch(error => console.log('error', error));
If you're simply looking to validate the Yelp api response then try running the request through a proxy that deals with the CORS policy for you like this:
var myHeaders = new Headers();
myHeaders.append("Authorization", "Bearer <MY_API_KEY>");
myHeaders.append("Cookie", "__cfduid=db290300ecfe95ec1fe3bc92c388c3c991586618117");
myHeaders.append("Access-Control-Allow-Origin", "*");
var proxyUrl = 'https://cors-anywhere.herokuapp.com/'
var targetUrl = 'https://api.yelp.com/v3/businesses/search?location=Houston'
var requestOptions = {
method: 'GET',
headers: myHeaders,
redirect: 'follow'
};
fetch(proxyUrl + targetUrl, requestOptions)
.then(response => response.text())
.then(result => console.log(result))
.catch(error => console.log('error', error));
The Access-Control-Allow-Origin is response header, it's mean that it does not matter in request, the server should allow to you make request.
is it API at yelp.com is allowed to you?

API request working in Postman but not in fetch() method of React Native app

I am trying to do a fetch() method in my React Native app:
return fetch(url, {
method: method,
headers: {
'Accept': 'application/json',
...headers
},
body: body
})
Here url is <IP address>:<port>/api/token
method is 'POST'
headers is {Content-Type: "application/x-www-form-urlencoded"}
and body is
grant_type=password&username=<username>&password=<password>&pushtoken=&primaryhost=<primary host IP>&primaryport=<primary host port>&secondaryhost=<secondary host IP>&secondaryport=<secondary host port>&osscustomer=103&deviceid=<device ID>&version=1.0&osversion=9&deviceversion=1.0
When I use these values in a Postman request, it works fine, but when I run the fetch() method in my React Native app, it gives the error e = TypeError: Network request failed at XMLHttpRequest.xhr.onerror.
Does anyone know why this might be?
change 'Accept' to Accept without single quites.
In the latest android versions http requests are not allowed by default. Take a look at this post for further information about allowing http request:How to allow all Network connection types HTTP and HTTPS in Android (9) Pie?
Use the following format:
fetch('https://mywebsite.com/endpoint/', {
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
firstParam: 'yourValue',
secondParam: 'yourOtherValue',
}),
});
Better to use axios for http/https requests:axios package
It's working fine for me. Try this it may help
const formData = new FormData();
formData.append('email', 'test#gmail.com');
formData.append('password', '123456');
fetch("https://test.com/api/login", {
method: 'post',
body: formData
})
.then(res => res.json())
.then(
(result) => {
console.log(result);
}).catch(err => {
console.log(err);
})

getting data with fetch is working but not with axios

I can get my data with fetch
let myHeaders = new Headers();
myHeaders.append('X-Auth-Token', token,);
myHeaders.append('Content-Type', 'application/json');
fetch("myUrl", {
withCredentials: true,
headers: myHeaders
}).then(function (response) {
console.log(response)
})
but fetching data is not working with axios. this is my axios code
const headers={
'X-Auth-Token': token,
"content-type":"application/json"
}
axios.get('myUrl',{headers:headers,withCredentials:true})
.then(response => {
console.log(response)
})
.catch(err => {
console.log(err)
});
I use it this way:
Check if your headers object is in good shape with a console log.
const headers = {
'X-Auth-Token': token,
'content-type': 'application/json'
};
console.log(headers);
const request = axios.create({
myUrl,
headers: myHeaders,
withCredentials: true
})
request.get() // If you add a string inside the brackets it gets appended to your url
.then(res => console.log(res))
.catch(err => console.log(err))
If the error you are getting is about CORS (Cross Origin Resource Sharing):
If you want to allow credentials then your Access-Control-Allow-Origin must not use *. You will have to specify the exact protocol, domain, port.
You need to set the server to allow your origin.
It's a very common problem and you will see it happen often. Read more about cors here:
https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS
https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Allow-Origin

Resources