No 'Access-Control-Allow-Origin' header in Angular - angularjs

I am using a REST API call to query all open issues in the JIRA server. Below is the query:
https://jiraserver/rest/api/2/search?jql=project IN ("Project Name") AND status IN (open)
When I pass the query in Google Chrome advanced REST client, I am able to get a JSON response but when I give this in a HTTP call in Angular.js it returns:
No 'Access-Control-Allow-Origin' header error.
I am new to Angular.js, and I am not able to recognize what is going wrong. Can someone help me out?

Access-Control-Allow-Origin
This comes when the server is configured for not to share data for cross domain requests.
When I pass the query in google chrome advanced rest client , am able to get a json response
Yes, All the rest clients can access data because they are allowed to do so, but for ajax You should enable the CORS to share data cross domain.
Another way is to create proxy
What one can do is, create a proxy at server which can in turn calls the other url and get the data and send it. You can do something like this:
<?php
// suppose this page as "proxy.php"
header('Content-Type: application/json');
$jsonData = json_decode(file_get_contents('https://jiraserver/rest/api/2/search?jql=project'));
echo $jsonData;
?>
Then in the ajax you can use ajax to send a request to this file:
$http({
method: 'POST',
url: '/proxy.php'
}).then(function successCallback(response) {
console.log(response);
}, function errorCallback(response) {
console.log(response);
});

Since JIRA 6.0 you could configure a whitelist for CORS, see JIRA-30371:
CORS has been supported in the JIRA REST API since JIRA 6.0 for JIRA Server. If you are a JIRA Server customer, simply go to the "Whitelist" section of JIRA Administration and add the domains you wish to request resources from. Note: You must have the System Administrator global permission to access this section of JIRA administration.
Unfortunately, this domain whitelist is not available in JIRA Cloud for security reasons. We are currently exploring alternative ways to allow certain requests that would not expose JIRA to this attack vector. I will update this issue as soon as we have more information.
See also: Configuring the Whitelist

Related

CORS errors when trying to fetch from new Google Cloud API Gateway

I was testing out the new API Gateway to secure a cloud function for my React application. So far the process has been much nicer than the previous alternatives, but I am currently getting CORS errors when trying to reach out to my API Gateway from my React app. I am setting the CORS headers correctly in my Cloud Function, but I have no known way of doing the same on the API Gateway endpoint. I am using Postman to test a request to the gateway endpoint and everything is working great, so it is just when I request from my React app.
Error: "Access to fetch at 'https://my-gateway-a12bcd345e67f89g0h.uc.gateway.dev/hello?key=example' from origin 'https://example.netlify.app' 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."
Would love some insight into this issue. Thanks!
This is not yet supported, however, there is a temporary workaround to get this working. You should add options to the paths in your openapi.yaml. Additionally, both get and options operations should point to the same cloud function, since the options request then acts as a warmup request for the cloud function. This is the most efficient setup, in terms of latency. Here is a simplified example:
paths:
/helloworld:
get:
operationId: getHelloWorld
x-google-backend:
address: $CLOUD_FUNCTION_ADDRESS
responses:
'200':
description: A successful response
options:
operationId: corsHelloWorld
x-google-backend:
address: $CLOUD_FUNCTION_ADDRESS
responses:
'200':
description: A successful response
Then, in your cloud function backend, you must also handle the preflight request (source). The Google documentation also provides an example with authentication, which has some additional headers. Here is an example without authentication:
def cors_enabled_function(request):
# For more information about CORS and CORS preflight requests, see
# https://developer.mozilla.org/en-US/docs/Glossary/Preflight_request
# for more information.
# Set CORS headers for the preflight request
if request.method == 'OPTIONS':
# Allows GET requests from any origin with the Content-Type
# header and caches preflight response for an 3600s
headers = {
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': 'GET',
'Access-Control-Allow-Headers': 'Content-Type',
'Access-Control-Max-Age': '3600'
}
return ('', 204, headers)
# Set CORS headers for the main request
headers = {
'Access-Control-Allow-Origin': '*'
}
return ('Hello World!', 200, headers)
Note: the downside of API gateway not managing preflight requests in a proper manner results in a penalty of running the cloud function twice. But your second request should always be very fast since the first request acts as a warmup request.
Turns out that API Gateway does not currently have CORS support.
Reference.
Solution
Here is the solution. It is just as user14982714 stated. Add a host and x-google-endpoints to your oepnapi.yaml file at the top level:
host: my-cool-api.endpoints.my-project-id.cloud.goog
x-google-endpoints:
- name: my-cool-api.endpoints.my-project-id.cloud.goog
allowCors: True
However, be sure to replace my-cool-api.endpoints.my-project-id.cloud.goog with your API Managed Service URL. This can be found in your google cloud console under the API Gateway API here:
I covered the start to my endpoint name for privacy, however, yours should also end with .cloud.goog. If you haven't deployed a configuration yet, deploy it without the x-google-endpoints and host, then update it to include both. (To update your configuration go to API Gateway -> Your API -> Gateways Tab -> Your Gateway -> Edit- > Change API Config -> Create New)
Explanation
Now to explain why this works with Google Cloud API Gateway. The API Gateway uses endpoints under the hood. Most people don't know this is the case, however, after giving up on the API Gateway and moving back to Endpoints I noticed that my API Gateways were listed under the endpoint services. They do not show in the UI, but with the gcloud CLI, run this command gcloud endpoints services list and you should see your API Gateways. Crazy! But Google does this a lot.
So knowing this I tried adding allowCors: true to the x-google-endpoints and viola. It worked. I hope this helps someone out there.
swagger: "2.0"
host: "my-cool-api.endpoints.my-project-id.cloud.goog"
x-google-endpoints:
- name: "my-cool-api.endpoints.my-project-id.cloud.goog"
allowCors: True
Note: host and name should have the same API endpoint name
Configuring these lines in your config file enables CORS for API GATEWAY
[Reference][1]
[1]: https://cloud.google.com/endpoints/docs/openapi/support-cors#:~:text=CORS%20(Cross%2Dorigin%20resource%20sharing,would%20prevent%20cross%2Dorigin%20requests.
I had the same issue and solve it with a load balancer (originally used to add a custom domain to my API gateway).
I use my load balancer to add the missing header into the response.
You just need to add the "Access-Control-Origin" header:
Allow all
Access-Control-Origin:'*'
Allow a specific origin
Access-Control-Allow-Origin: http://example.com:8080
You can find the instructions here GCP - Creating custom headers.
If you do not have a load balancer implemented,
you can follow this tutorial to implement a new one Google API Gateway, Load Balancer and Content Delivery Network.
You can find more information regarding CORS at https://www.w3.org/wiki/CORS_Enabled.
I had similar issue with other API so I am not sure the same will work in your case but you can try - in react app when fetching the data, lets say with axios you can try
axios.post('http://localhost:3003/signup',this.data,{headers:{'Access-Control-
Allow-Origin':'*','Content-Type': 'application/json'}})
on the backend side - try this -
let cors=require('./cors')
app.options('*', cors());
It works in my case , hope it will help you.

Angular JS. Request header field Access-Control-Allow-Origin is not allowed by Access-Control-Allow-Headers in preflight response

I have tried all things, use CORS plugin. disable web-security in chrome.
The response is coming in POSTMAN but not able to fetch it in $http.
$http({
url: "https://interview-api-staging.bytemark.co/books",
method: 'GET',
headers: {
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': 'OPTIONS,POST,GET,OPTIONS,PUT,DELETE',
'Access-Control-Allow-Headers': 'Authorization,Content-Type,Accept,Origin,User-Agent,DNT,Cache-Control,X-Mx-ReqToken,Keep-Alive,X-Requested-With,If-Modified-Since'
}
}).then(function(d) {
console.log(d);
});
Client has nothing to do with it. With a CORS header, you're telling the client which other servers do I trust. Those then can share your resources and client won't mind.
For example if you have two domains you tell the client so let your resources be used by your second website, you don't say I trust you as a client.
So you're protecting the server, not client. You don't want AJAX API Endpoints to be accessible by scripts hosted anywhere in the world.
A client has nothing to gain/lose from this. It's only a protection for servers because using AJAX all the URLs are clearly visible to anyone and had it been not for this protection, anybody could go-ahead run their front end using your API, only servers have to lose from this so they get to decide who can use their resources.
source.
As mentioned you don't need to do any cors related stuff in the front-end. Make sure the cors headers are sent from the backend in its response headers.
It is the server that has to protect itself so they have to tell some rules to the client which client will follow. By default, the client will accept everything.
Use CORS in your backend. Otherwise, you can check out Allow-Control-Allow-Origin: * in the Chrome Web Store, use chrome extension.
when you trying to hit through the angular app you need to turn on that extension.
otherwise you need to active CORS in your backend application

Recaptcha request from production server

I am using CORS plugin for chrome and it works fine when uses local machine, but in production server the error occurs:
No 'Access-Control-Allow-Origin' header is present on the requested
resource. Origin is therefore not allowed access.
I understand the problem, that domain server different from domain to send request, also I understand that all users will not add CORS plugin to avoid chrome specific features.
So how do I can off checking for Access-Control-Allow-Origin for concrete post request? Use Angular to send request.
return $http({
method: 'POST',
url: url,
headers:{
'Content-Type': "application/x-www-form-urlencoded"
},
data: $.param(data)
});
I need to avoid this error on prod server.
I just ran into this issue a few days ago and searched everywhere for a response. From what I gathered, the only way to do a cross-domain AJAX request is if you have control of both of the servers hosting each domain. This way you can add the necessary headers in the HTTP requests to allow for cross-domain requests. If you don't have control of both servers, you can POST to a PHP script on your server that can then POST externally and return the info you need. That's how I resolved my issue anyway. hope it helps!

Get a "Response header" Cookie from angular $http POST request

I'm writing a small app using angular.
I need to access a couch database. I only have a user in that DB.
Using cURL commands I can request a session cookie to that database and that use that cookie to request a specific document.
When in angular code I use:
$http.post(url, data).then(...);
Where 'data' has username and password, I can see the cookie using chrome (like in this image chrome dev tool output), but in a code, I can't access it.
Can someone help me with this?
You can not access an HttpOnly cookie using script in browser due to security reasons. It can only be accessed on server.
If you need to include cookies in cross domain requests use withCredentials in the request. See $http docs
$http.post returns a response with a property:
headers – {function([headerName])} – Header getter function.
So you should be able to do something like
.then((response) => {
console.log(response.headers('set-cookie'));
});
See the documentation here
Try to use response.headers('set-cookie')
For the crossdomain situation, the server has to send
Access-Control-Expose-Headers: set-cookie header to make the custom headers visible.
https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS#Access-Control-Expose-Headers

Angular, Cannot make an an API call probably because of CORS issue

I am trying to make an Angular application consuming Foreign Exchange (forex) market API.
$http({
method: 'GET',
url: 'http://www.apilayer.net/api/live?access_key=[MY ACCESS KEY]'
}).then(function(response){
console.log(response);
})
I keep getting the following error when I look at the browser console.
Request header field Authorization is not allowed by Access-Control-Allow-Headers in preflight response.
The weirdest part is that it used to work - I was able to retrieve JSON info from the API call without a problem, but it does not any more.
Is there anyone who can point me to a set of possible causes? Would appreciate it!
If you didn't change anything in your code (say, the path for the api) then it must be one of two thing:
The browser configuration has changed
The api provider has blocked cross domain request, you should contact him, maybe he require callback with jsonp ajax request

Resources