No Access Control Origin is not detected reactjs - reactjs

I am trying to pull API data and when I do, I get the error message of "No Access Control Origin detected" even though I add a Access Control Allow Origin header
When I npm start in Chrome/Firefox it doesn't work but when I use IE it does work
Here is my code:
componentDidMount() {
fetch(url , {
mode: 'cors',
headers: {
'X-API-KEY': API_KEY,
'Access-Control-Allow-Origin': 'https://localhost:3000/',
'Access-Control-Allow-Credentials': 'true',
'Access-Control-Allow-Headers': 'Content-Type, Origin, Accept, Authorization',
'Accept': 'application/json',
'Content-Type': 'application/json'
}
})
.then(res => res.json())
.then(json => {
this.setState({
isLoaded: true,
items: json,
})
})
};

I would think this is a server side issue with the API you are using. Make sure that option request have the proper Access-Control headers and can accept your request.

Related

React Native - Fetch Problem: TypeError: NetworkError when attempting to fetch resource. ‘Access-Control-Allow-Origin’

I have a problem. I call/request url in this code;
fetch("http://url",{
method:'GET',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json'
}
})
.then(res=>
console.log(res)
)
.catch(error => console.log(error))
But i get the error:
TypeError: NetworkError when attempting to fetch resource.
And i am checking console network then i see CORS failed.
Can you help me ?
Thank you
I fixed it. If I call/request with an android device, it's not a problem.
But if I call/request with the web, that's time get the error.
That's why I am not using a web interface.
An edit of my code:
fetch("http://url",{
method:'GET',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json'
}
})
.then(res=> res.json())
.then(res=>{
console.log("ImageUrl: ", res);
})
.catch(error => console.log(error))

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

React native fetch() 403 status

I have an API endpoint working good in postman with the bellow options
The above request can get 200 status and got a response. Now I am trying to implement the same API with React Native using fetch method.
fetch('https://example.com/api/user/login', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Token':'xxxxxx-xxxx-xxxx-xxxx-xxxxx'
},
body: {
"useremail": "testuser#example.com",
"userpassword": "123456"
},
})
.then((response) => response.json())
.then((responseJson) => {
console.log(responseJson);
}).catch((error) =>{
console.error(error);
});
The above code was not working and I am getting 403 status.
Have you tried this
The easy way to implement this is to use this attribute to your AndroidManifest.xml where you allow all http for all requests:
android:usesCleartextTraffic="true"
feel free for doubts
You are passing data without converting it to json will make problem here
fetch('https://example.com/api/user/login', {
method: 'POST',
credentials : 'include',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
'token':'xxxxxx-xxxx-xxxx-xxxx-xxxxx',
},
body: JSON.stringify({ // convert object to json
"useremail": "testuser#example.com",
"userpassword": "123456"
}) ,
})
.then((response) => response.json())
.then((responseJson) => {
console.log(responseJson);
}).catch((error) =>{
console.error(error);
});
HTTP 403 is a standard HTTP status code communicated to clients by an HTTP server to indicate that access to the requested (valid) URL by the client is Forbidden for some reason. The server understood the request, but will not fulfill it due to client related issues.
so for first step in your postman use a fake user password to see if you get 403 again ,
if you got, that means you have problem in your sending your react native data.
so you should focus on your sending request code then,
According to docs
you can post like this
fetch('https://mywebsite.com/endpoint/', {
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
firstParam: 'yourValue',
secondParam: 'yourOtherValue',
}),
});
be sure that you are sending your user pass correctly and not missing anything like misspellings
hope this helps you.

Axios api call returns not found error in reactjs

I'm requesting post axios call with 2 parameters.
export const getUser = (page,Type) => {
axios.post(APIURL.apiURL,
{
page: page,
auth: Type
}, {
headers: {
'Access-Control-Allow-Origin': '*',
'Content-Type': 'application/json',
}
}).then(res => {
console.log(res);
}).catch(err => {
console.log(err);
});
}
I tried both version but returns Http request blocked by CORS Policy.Is there any other way to send body in axios call.
Try to add this to request headers:
"Access-Control-Allow-Origin": "*"
If not, then you need to proxy the request somehow. The easiest way to do it in this scenario is to use the 'http-proxy-middleware' npm package
You have to allow origin from back-end side. It's not an issue of front-end code.
You have to add below lines in your API middleware at backend.
'Access-Control-Allow-Methods': 'POST, GET, PUT, OPTIONS, DELETE'
'Access-Control-Allow-Origin': '*'
'Access-Control-Allow-Credentials': ' true'

Post data with By posting data with 'content-type': 'application/x-www-form-urlencoded' and 'key': 'key'

I want to post data to the server using headers content-type: 'application/xww-form-urlencode' but it fails because of the content type change to application/json
var headers= {
'content-type': 'application/x-www-form-urlencoded',
'x-access-key': 'key'
}
var data = {
'twins' : twins
}
axios.post('url', data, { headers: headers })
.then((response) => {
console.log(response)
})
.catch((error) => {
console.log(error)
})
With Postman I successfully added the entry
In your headers change content-type to
'Content-Type': 'application/x-www-form-urlencoded'
If this doesn't work, then you I feel you might be using an interceptor. Which might be overriding your configuration.

Resources