Can't fetch data from Api using Axios (with no server) - reactjs

So, I'm working on a task, which says to fetch data using Axios, but without mentioning using a server, And when I tried to fetch data using Axios I got an error. The error is:
Access to XMLHttpRequest at 'https://api.first.org/data/v1/teams' 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.
And here is my code in ASP React:
useEffect(()=>{
var config = {
method: 'get',
url: 'https://api.first.org/data/v1/teams',
headers: {
'Access-Control-Allow-Origin' : '*',
'Access-Control-Allow-Methods': 'GET, PUT, POST, DELETE, PATCH, OPTIONS',
'Access-Control-Allow-Credentials': true
},
};
axios(config)
.then(function (response) {
console.log(JSON.stringify(response.data));
})
.catch(function (error) {
console.log(error);
});
},[])
So my real question is, Can I get it to work without using a server, and I want to learn if this does and can work without a server. Because it's an Open API, and using Postman it's working, but when I do request Isn't.

There are two suggestion way from me, if you want to try axios but no deployed server.
Using axios-mock-adapter, so you can perform api call without using deployed server, but you have to mock to request by yourself. https://www.npmjs.com/package/axios-mock-adapter
Self-serving server in localhost, maybe you can use json-server and access it via localhost https://www.npmjs.com/package/json-server

Related

How to handle CORS Policy when use fetch function on ReactJs

need help for ReactJs. I still learning reactJs to fetch data from PHP backend. I'm using Xampp as my local server. but when i integrate fetch function on ReactJs, i got CORS policy error.
here is my code from on my App.jsx
useEffect(() => {
fetch("http://localhost:81/opencart/index.php?route=api/create", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ items: [{ id: "xl-tshirt" }] }),
})
.then((res) => res.json())
.then((data) => setClientSecret(data.clientSecret));
}, []);
On my reactJs package.json file i added this
"proxy": "http://localhost:81/"
but still display error on browser console
Access to fetch at 'http://localhost:81/opencart/index.php?route=api/create' 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.
How do I resolve this?
CORS issue is definitely coming from Server. So the ideal way is to set your server to accept your request from cross origin.
Seems you are working with server built with PHP, then check your backend server to add CORS configuration.
For Express.js and others are having several way to add it such as adding 'cors` middleware.

API cs-cart put request by react and axios

I use react in front-end and cs-cart API in back-end.
In the following code I used axios.put() as follows:
const data = JSON.stringify({
"test1": "val1"
});
const config = {
method: 'put',
url: 'https://example.com/api/product/111',
headers: {
'Authorization': `Basic ${token}`,
'Content-Type': 'application/json'
},
data : data
};
axios(config)
.then(res => {
console.log(res)
});
When sending a request, the browser sends a request with the OPTIONS method, which error: 405
Method Not Allowed returns.
And the original request (PUT) is not sent.
cs-cart is installed on the server. And the react project on localhost
Have you made sure to understand the error correctly i.e
The HyperText Transfer Protocol (HTTP) 405 Method Not Allowed response
status code indicates that the server knows the request method, but
the target resource doesnt support this method.
The server must generate an Allow header field in a 405 status code
response. The field must contain a list of methods that the target
resource currently supports.
Make sure that the server is able to understand how to interpret your request so the clients are able to proceed.
You can look at this in more detail below here.

.. from origin .. has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status

I'm fairly new to making API requests. I'm am trying to set up an incoming slack webhook using a simple axios post request from my React project, however I keep receiving the CORS policy error. The request works perfectly in insomnia.
I'm using ngrok to expose my web server running on my local machine to the internet (I assumed this would correct the issue.) So I'm making the request from https://...ngrok.io, however I'm still receiving 'Status Code: 400' in my network tab along with the error above.
axios({
method: "post",
url:
"https://hooks.slack.com/services/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",
headers: { "Content-type": "application/json" },
data: { text: "Hello, World!" },
}).then(
(response) => {
console.log(response);
},
(error) => {
console.log(error);
}
);
};
There are similar errors on stackoverflow, but none fix my error. I'd really like to understand why this is happening so any advice would be appreciated.
Fixed it, for those having the same issue:
What worked for me is setting Content-Type header to application/x-www-form-urlencoded. found it in this thread: https://github.com/axios/axios/issues/475 It appears that this triggers "simple request" and therefore avoids triggering CORS preflight. https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS#Simple_requests

Failed to upload data from heroku app. CORS error

I'm trying to fetch my data from a heroku app into Redux, but I think I'm running into a CORS issue. I've been playing with "headers" for a while and still can't figure it out.
This is the exact error:
"Failed to load https://name-app.herokuapp.com/users: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled."
And this is my code:
export function fetchMicros() {
return dispatch => {
const url = "https://name-app.herokuapp.com/users";
return fetch(url, {
method: 'GET',
mode: 'cors',
headers: { 'Content-Type': 'text' },
})
.then(handleErrors)
.then(res => res.json())
.then(micros => {
dispatch(fetchVitamins(micros));
}
)};
};
If you don't have to do any authentication nor need to pass any data, you can do a no-cors request (more information on mdn page).
fetch(url, {
mode: 'no-cors',
})
If you do need cookies or some kind of authentication, then you need to make the server accept your domain and request methods on the preflight response.
In the event that you don't have access to change that on the server, you can create a nodejs server that will handle the calls for you, bypassing any cors checks (only browser cares about cors, servers don't).

Authentication Error when using mode: no-cors using fetch in React

I am building a React app that is pulling different stats from services for our internal developers (commits, tracked hours, etc)..
I am using fetch to grab API data from Harvest, a time tracking app. According to their docs, you can use basic HTTP authentication. When I use the app Postman, all is well and I can see the response just fine. Initially I used:
getHarvest(){
// Set Harvest Headers
const harvestHeaders = {
method: 'GET',
headers: {
'Authorization': 'Basic xxxxxxxxxxxxxxx=',
'Content-Type': 'application/json',
'Accept': 'application/json',
'Cache-Control': 'no-cache',
}
};
fetch('https://factor1.harvestapp.com/projects/', harvestHeaders)
.then( response => response.json() )
.then( projects => {
// Do some stuff
} )
}
This gives me an error in the console:
Fetch API cannot load https://myaccount.harvestapp.com/projects/.
Response to preflight request doesn't pass access control check: No
'Access-Control-Allow-Origin' header is present on the requested
resource. Origin 'http://localhost:3000' is therefore not allowed
access. The response had HTTP status code 404. If an opaque response
serves your needs, set the request's mode to 'no-cors' to fetch the
resource with CORS disabled.
So with that feedback I changed the function to look like this:
getHarvest(){
// Set Harvest Headers
const harvestHeaders = {
method: 'GET',
mode: 'no-cors',
headers: {
'Authorization': 'Basic xxxxxxxxxxxxxxx=',
'Content-Type': 'application/json',
'Accept': 'application/json',
'Cache-Control': 'no-cache',
}
};
fetch('https://factor1.harvestapp.com/projects/', harvestHeaders)
.then( response => response.json() )
.then( projects => {
// do stuff
} )
}
But that results in an Authentication error:
GET https://myaccount.harvestapp.com/projects/ 401 (Unauthorized)
I'm not sure how I can get the response correctly. Am I doing something wrong? It seems odd to me that using the app Postman works but this doesn't. Thoughts? Thanks!
It doesn’t seem like the Harvest API is meant to be used with XHR or Fetch from Web applications.
At least their docs don’t mention anything about using their API from XHR or Fetch, nor do those docs mention anything about Access-Control-Allow-Origin nor CORS in general.
Instead the docs give examples of using the API with curl and with the Postman REST Client.
And trying examples in the docs like below, the response has no Access-Control-Allow-Origin.
curl -H 'Content-Type: application/xml' -H 'Accept: application/xml' \
-u "user#example.com:password" https://example.harvestapp.com/account/who_am_i
So it seems like the answer is: You can’t access the Harvest API with XHR/Fetch from a Web app.
It works in Postman because Postman is not bound by the same-origin policy browsers enforce to prevent Web apps running in a browser from making cross-origin requests unless the site/endpoint the request is made to has opted in to using CORS (which it seems Harvest hasn’t opted into).

Resources