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.
Related
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.
When I attempt to request a lambda-backed API (using API gateway, deployed using the CLI and Cloud Development Kit) from my react app, I get the following error:
Access to XMLHttpRequest at 'https://xxxxxxxxxx.execute-api.eu-west-1.amazonaws.com/prod/xxxxx' 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.
GET https://xxxxxxxxxx.execute-api.eu-west-1.amazonaws.com/prod/xxxxx net::ERR_FAILED
My API resources defined using the CDK are all passed into this method
Like explain here, you need to enable CORS in API Gateway, BUT you also need to return an Access-Control-Allow-Origin header from your Lambda because API Gateway doesn't add that automatically to the responses.
Here is a sample of what my Lambda return for a simple Get :
return {
headers,
body: JSON.stringify(response.Item),
statusCode: 200
};
const headers = {
"Access-Control-Allow-Origin": "*", // Required for CORS support to work
"Access-Control-Allow-Credentials": true // Required for cookies, authorization headers with HTTPS
}
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
I have seen dozens of questions on SO and different blogs talking about this with "answers" -- all to no avail.
I have a React.js app on my local machine (Ubuntu 16.04). Locally, I try to test it by running npm start and it opens up the browser to http://localhost:3000.
On one page, I am trying to access my PHP api which is on my shared hosting server.
Chrome and Firefox both say that it fails due to server not having Access-Control-Allow-Orgin.
Exact Message:
Failed to load http://---/api/v1/categories: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost.com: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.
localhost.com/:1 Uncaught (in promise) TypeError: Failed to fetch
However, upon my php server entry point I do have:
header("Access-Control-Allow-Orgin: *");
header("Access-Control-Allow-Methods: *");
Here is where I make my api call in my react app:
componentDidMount() {
var options = {
method: 'get',
headers: {
"Access-Control-Request-Headers": "*",
"Access-Control-Request-Method": "*"
},
}
// I have since removed the headers from the options as advised in the comments
fetch('http://---/api/v1/categories', options)
.then(results => {
return results.json();
}).then(data => {
let categories = data.map((category) => {
return(
// edited out
)
})
this.setState({categories: categories});
})
}
}
I have tried this on both Chrome and Firefox; I have also tried to alias my server away from localhost. I have tried the no-cors approach, which does get me access -- but breaks everything of course. I have tried with and without passing headers along with my fetch request.
UPDATE:
I did get it to work by installing this Chrome plugin. I feel this is a workaround and would like to know if there is a coding answer here.
I'm an idiot.
Origin was misspelled as Orgin.
This typo has existed in my project for almost three years. This was the first time I needed to use cross-domain access.
header("Access-Control-Allow-Methods: *");
Should be:
header("Access-Control-Allow-Methods: GET, POST, HEAD, OPTIONS, PUT, DELETE, PATCH");
...and any other methods you intend to accept.
I added CORS extension to chrome. When called ajax from localhost I got response in the form of XML. If I disabled CORS extension I got the following error. I referred so many questions in this community. But I cant't resolve my problem. It may duplicate but I'm asking this question for help with hope.
XMLHttpRequest cannot load https://buzz.machaao.com/feed. 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 401..
And my code is
HTTP.get('https://buzz.machaao.com/feed',{
headers: {
"Access-Control-Allow-Origin" : "*"
}
}, (err, res) => {
if(err) {
console.log(err);
}
else {
console.log(res);
}
});
The https://buzz.machaao.com/feed site doesn’t send the Access-Control-Allow-Origin response header, so you need to make your request through a proxy instead—like this:
var proxyUrl = 'https://cors-anywhere.herokuapp.com/',
targetUrl = 'http://catfacts-api.appspot.com/api/facts?number=99'
HTTP.get(proxyUrl + targetUrl,
(err, res) => {
if(err) {
console.log(err);
}
else {
console.log(res);
}
});
https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS explains why browsers won’t let you access the response cross-origin from frontend JavaScript code running in a web app unless the response includes an Access-Control-Allow-Origin response header.
https://buzz.machaao.com/feed has no Access-Control-Allow-Origin response header, so there’s no way your frontend code can access the response cross-origin.
Your browser can get the response fine and you can even see it in browser devtools—but your browser won’t expose it to your code unless it has a Access-Control-Allow-Origin response header. So you must instead use a proxy to get it.
The proxy makes the request to that site, gets the response, adds the Access-Control-Allow-Origin response header and any other CORS headers needed, then passes that back to your requesting code. And that response with the Access-Control-Allow-Origin header added is what the browser sees, so the browser lets your frontend code actually access the response.