ReactJS API Data Fetching CORS error - javascript

I've been trying to create a react web app for a few days now for my internship and I've encountered a CORS error. I am using the latest version of reactJS, and placing this in the create-react-app, and below is the code for fetching:
componentDidMount() {
fetch('--------------------------------------------',{
method: "GET",
headers: {
"access-control-allow-origin" : "*",
"Content-type": "application/json; charset=UTF-8"
}})
.then(results => results.json())
.then(info => {
const results = info.data.map(x => {
return {
id: x.id,
slug: x.slug,
name: x.name,
address_1: x.address_1,
address_2: x.address_2,
city: x.city,
state: x.state,
postal_code: x.postal_code,
country_code: x.country_code,
phone_number: x.phone_number,
}
})
this.setState({warehouses: results, lastPage: info.last_page});
})
.then(console.log(this.state.warehouses))
}
I'm sorry that I can't post the url for the API due to company rules, however, it is confirmed that there are no CORS setting in the API backend.
However, I encounter the following errors when run on mozilla
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at ------------------. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing).
and
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at ---------------------------------------------. (Reason: CORS request did not succeed).
If run on chrome it gives the following error
Failed to load resource: the server responded with a status of 405 (Method Not Allowed)
and
Failed to load --------------------------------------------------------: 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 405. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
and
Uncaught (in promise) TypeError: Failed to fetch
Another thing is that I am able to open the url in my browsers with no problems or whatsoever.
Please help and thanks!
Additional Information
The reason I added the CORS setting is because it gives a CORS error, so removing it does not really solve the issue.
Next I tried to perform proxy setting, however, it now gives
Unhandled Rejection (SyntaxError): Unexpected token < in JSON at position 0
According to the internet this is caused becasue the response is not a JSON. However when I checked the API it gives this
api img
which means that return type should be a JSON right?
Additional Info
checking the respond will yield this
{"status":200,"total":1,"per_page":3,"current_page":1,"last_page":1,"next_page_url":null,"prev_page_url":null,"from":1,"to":3,"data":[{"id":1,"slug":"america","name":"america","address_1":"USA Court","address_2":"USA","city":"USA","state":"USA","postal_code":"94545","country_code":"US","phone_number":"10000001","created_by":null,"updated_by":null,"created_at":"2017-11-10 11:30:50+00","updated_at":"2018-06-28 07:27:55+00"}]}

The CORS settings need to be setup in the API to allow access from your React app domain. No CORS settings, no AJAX from different domains. It's simple as that. You can either add CORS settings to your company API (this is unlikely to happen) or you can work around like described below:
The CORS is solely a mechanism of client browser to protect users from malicious AJAX. So one way to work around this is proxying your AJAX request from your React app to its own web server. As Vincent suggests, the create-react-app provides an easy way to do this: in your package.json file, simply chuck "proxy": "http://your-company-api-domain". For more details, please see this link
Then in your react app you can using relative URL like this: fetch('/api/endpoints'). Notice that the relative URL has to match with your company API. This will send a request to your server, then the server will forward the request to your company API and return the response back to your app. Since the request is handled in the server-to-server way not browser-to-server so the CORS check won't happen. Therefore, you can get rid of all unnecessary CORS headers in your request.

This is what I did using vite
Package.json file add:
"proxy": "http://api_website_where_the_request_is_comming/",
App component or whatever component you making the call do this
let endpoint = /api/your_endpoint/;
fetch(endpoint).then(function (response) {
return response.json()
})
.then(function (jsonData){
console.log('Banner log', jsonData);
})

In your backend, make sure that the app is use cors.
Run this to install cors
npm install cors --save
Import cors in the app using
const cors = require('cors');
app.use(cors()) // if name of your backend is app

Related

How to force authentication in preflight request?

I'm trying to call Github REST API from client-side javascript (in browser).
My code does the following (I'm trying to get a zip containing the branch mkdocs_page of a private repository) :
const endpoint = 'https://api.github.com';
const resource = '/repos/astariul/private-gh-pages/zipball/mkdocs_page';
const options = {
mode: 'cors',
headers: {
'Authorization': 'Basic ' + btoa(`${pat}`), // pat contains my Personal Access Token
}
}
return fetch(`${endpoint}${resource}`, options);
But it does not work :
The preflight request fails with 404.
The console error message :
Access to fetch at 'https://api.github.com/repos/astariul/private-gh-pages/zipball/mkdocs_page' from origin 'null' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status.
In the process of debugging this, I tried to reproduce the problem with curl. And when I specify an authenticated request, it works :
curl --user "<my_PAT_token>" -i https://api.github.com/repos/astariul/private-gh-pages/zipball/mkdocs_page -X OPTIONS
HTTP/1.1 204 No Content
But if the request is not authenticated, it does not work :
curl -i https://api.github.com/repos/astariul/private-gh-pages/zipball/mkdocs_page -X OPTIONS
HTTP/1.1 404 Not Found
Note : it works fine when I'm trying to get the master branch (authenticated or not). However it fails after, when being redirected :
Access to fetch at 'https://codeload.github.com/astariul/private-gh-pages/legacy.zip/refs/heads/main?token=XXX' (redirected from 'https://api.github.com/repos/astariul/private-gh-pages/zipball') from origin 'null' 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.
Is it a bug in the Github API ? Or I'm doing something wrong ?
There’s no way to force authentication in a preflight request. The preflight is controlled totally by the browser, and nothing about it is exposed in any way that you can manipulate from frontend JavaScript code. And the requirements for the CORS protocol explicitly prohibit browsers from including any credentials in preflight requests.
For a detailed explanation, see the answer at https://stackoverflow.com/a/45406085/.
Since the preflight involves the browser making an OPTIONS request, then in general, if a server requires authentication for OPTIONS request to a particular resource (which seems to be the case for the GitHub URL cited in the question) that’s not at all necessarily an unintended bug.
That’s because the only normal case in which a preflight is performed and an OPTIONS request is sent is for the case of frontend JavaScript code running in a browser. Requests made from server-side code or from code running in shell/command-line environment or from desktop apps or native mobile apps don’t involve sending an OPTIONS request.
So, lack of support for unauthenticated OPTIONS requests to a particular resource would only be a bug if the provider actually intended it to be used from frontend code running in a browser. In other words, it can instead indicate the provider intentionally doesn’t want it to be used from frontend JavaScript code (which seems to be the case for the URL cited in the question).

Evernote authentification with developer token failed

I'm writing totally simple JS code to connect to the Evernote sandbox, which is pretty the same as the one in the documentation:
const Evernote = require("evernote");
const client = new Evernote.Client({
token: "here-is-my-developer-token1234",
sandbox: true
});
const userStore = client.getUserStore();
userStore.getUser().then(function(user) {
console.log(user)
});
Though, I get an error about the CORS policy, which, I suppose, means that my authentification failed for some reason:
Access to fetch at 'https://sandbox.evernote.com//edam/user' from origin 'http://127.0.0.1:5500' 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.
I've got my token from there: https://sandbox.evernote.com/api/DeveloperToken.action
Perhaps there is something basic I'm missing. Any guidance would be appreciated.
As you can see in JS SDK docs, they do not support CORS, that is, header authentification as well. So you will need to use oauth.

How do I fix CORS blocked error when uploading to Cloudinary

I'm making a personal website and need users to upload files to Cloudinary with signed uploads. My code is
const cloudinary = require('cloudinary/lib/cloudinary').v2;
cloudinary.config({
cloud_name: 'cloud_name',
api_key: 'api_key',
api_secret: 'api_secret'
});
cloudinary.uploader.upload(image,{public_id: id}, function(error, result) { });
Whenever I run cloudinary.uploader.upload i get this error in the browser
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://api.cloudinary.com/v1_1/cloud_name/image/upload. (Reason: header ‘user-agent’ is not allowed according to header ‘Access-Control-Allow-Headers’ from CORS preflight response).
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://api.cloudinary.com/v1_1/cloud_name/image/upload. (Reason: CORS request did not succeed).
Same thing happened to me then I realized I forgot to add the API keys and secret environment variables to my deployed code. A CORS error just seems to pop up whenever there is an uncaught error.
If you already have CORS enabled in the server and everything looks right with "CORS" then it is probably some other error.
Edit: Just to add to this, after I put in the correct api keys, I still had the same problem. It turns out that I was using firebase functions and it was weird with multer. I changed from multer to busboy and everything worked perfectly. See link: https://stackoverflow.com/a/47603055/15560288

Accessing Jenkins API using Javascript

As titled,
I tried to access the Jenkins API (Jenkins latest version, which is 2.204.1) using the Jenkins library. I tried to make a call to retrieve the build log using the following code in React
import Jenkins from 'jenkins'
// ngrok is used to expose Jenkins's URL to the internet, so that Github webhooks can connect properly to the Jenkins.
const jenkinsConfig = {
baseUrl : 'http://username:password#URLToMyJenkins.ngrok.io',
crumbIssuer: true
};
const _jenkins = Jenkins(jenkinsConfig);
useEffect(() => {
const getBuildLog = () => {
runner.build.get({
name: 'jobname',
number: 1
}, (err, data) => {
if (err){
console.log('Its on err!!! ::: ', err);
}
console.log('Can i see what is the data ::: ', data);
});
}
}, []);
When i run the above code, it throws me the CORS error, but on the ngrok console, i can see that the API was successfully called (status 200)
OPTIONS /job/GHTest2/1/api/json 200 OK
On the web console
Access to fetch at 'http://URLToMyJenkins.ngrok.io/job/GHTest2/1/api/json' 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.
I installed Jenkins CORS-Filter-Plugin, and put the following configs onto it
Access-Control-Allow-Origins - http://localhost:3000, http://URLToMyJenkins.ngrok.io
Access-Control-Allow-Methods - GET, PUT, OPTIONS
Access-Control-Allow-Headers - origin, Content-Type, X-Requested-With
Access-Control-Expose-Headers - origin, *
Access-Control-Max-Age - 999
And even disable the security and CSRF protection in Jenkins, still didnt work and keep hitting the CORS error.
Did i do anything wrong here, or Jenkins API simply is not accessible from the frontend side using Javascript?
Managed to solve this by setting the following on Jenkins's CORS configuration
Access-Control-Allow-Headers - Authorization
With that, all the codes above finally can work as expected.

Angular app sends just option request without post [duplicate]

This question already has answers here:
How does the 'Access-Control-Allow-Origin' header work?
(19 answers)
Closed 3 years ago.
I'm making an app in angular 7 that connects to API that I wrote in python. I want to send a text in POST request and API does some nlp stuff and returns the result. API is using RestPlus and is hosted on GCP App Engine. So in angular I have this code:
posts: any;
readonly ROOT_URL = 'XXX';
const httpOptions = {
headers: new HttpHeaders({
'Access-Control-Allow-Origin': '*',
'Content-Type': 'application/json',
'X-API-KEY': 'X',
})
};
const data: any = {
"article": this.text
};
this.posts = this.http.post(this.ROOT_URL, data, httpOptions);
this.text is a value I get from form and I've already checked if it's valid. X-API-KEY is a token I set in API.
In console I get:
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at XXX. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing)
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at XXX. (Reason: CORS request did not succeed).
I tried sending a post request to postb.in to test it and got the same errors. And postb.in shows that it only received OPTION requests.
Cross origin request means that you are trying to make an API call to a server which is not your origin (this server is not rendering the front-end/client-end).
Example: If http://localhost/dummy-app delivers the front-end and you are trying to make an API call from this front-end to http://localhost:3000/dummy-api, it will result in a CORS issue.
Resolutions:
Render the front-end from the server where the API end point exists. This is only a technical solution and may not be a good architecture or not even possible at times.
Allow CORS in server. (Not highly recommended)
Use a middleware server to render your front end. This server can have an API endpoint through which you can pass the request to desired API. CORS issue appears to be a blocking by the browser and appears only when an external API is called from front-end. You can call an API in the middleware server which then further calls the external API.
Recommended : Use your web server to do the job. For example, create a new route in Nginx which proxy passes your request to the API.
location /api{
proxy_pass http://localhost:3000
}
In this method http://localhost/dummy-app can call the API as http://localhost/api/dummy-api.

Categories