In my angular controller code my http get method not working with header but the same request working in postman
$http({
method: 'GET',
url: 'http://localhost:8080/api/profiles',
headers: {
'Authorization': 'Bearer 78954642-sf25-4sd6-sdf2-99582369d5af',
'Content-Type':'text/plain'
}
}).then(function(success) {
console.log(success);
}, function(error) {
});
Showing following error
Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://quotebuilder' is therefore not allowed access. The response had HTTP status code 401.
My request header
OPTIONS /api/profiles HTTP/1.1
Host: localhost:8080
Connection: keep-alive
Pragma: no-cache
Cache-Control: no-cache
Access-Control-Request-Method: GET
Origin: http://quotebuilder
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36
Access-Control-Request-Headers: authorization
Accept: */*
Referer: http://quotebuilder/login
Accept-Encoding: gzip, deflate, sdch, br
Accept-Language: en-US,en;q=0.8
What is wrong here ? please help me to resolve the issue
Your should make CORS disabled in your server side to make this work. A resource makes a cross-origin HTTP request when it requests a resource from a different domain, or port than the one which the first resource itself serves see dtails here. If you are using spring or other server side web frameworks you need to disable that from there.
Related
I have been trying to use the following code using React fetch to get a response from the OpenWeather API:
fetch('api.openweathermap.org/data/2.5/weather?q=Milwaukee&APPID=1234567890')
.then(response => response.text())
.then(data => {
console.log(data)
When I skip react and just copy the url (api.openweathermap.org/data/2.5/weather?q=Milwaukee&APPID=1234567890) into the browser I get a totally valid response. (For example ) When I use the fetch code in my React application, however, I get the following error:
Request URL: http://localhost:3000/api.openweathermap.org/data/2.5/weather?q=Milwaukee&APPID=1234567890
Request Method: GET
Status Code: 431 Request Header Fields Too Large
Remote Address: 127.0.0.1:3000
Referrer Policy: no-referrer-when-downgrade
I am running my react application off localhost from create-react-app. Why can I access that API just fine from my browser but get an error in my app?
Extra Information
In case it is useful here is the link to sign up for a free OpenWeather API
Here is the rest of the information from the response header:
HTTP/1.1 431 Request Header Fields Too Large
x-powered-by: Express
connection: close
date: Wed, 18 Sep 2019 15:45:21 GMT
transfer-encoding: chunked
Or from the request header:
GET /api.openweathermap.org/data/2.5/weather?q=Milwaukee&APPID=1234567890 HTTP/1.1
Host: localhost:3000
Connection: keep-alive
Sec-Fetch-Mode: cors
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.132 Safari/537.36
Accept: */*
Sec-Fetch-Site: same-origin
Referer: http://localhost:3000/
Accept-Encoding: gzip, deflate, br
Accept-Language: en-US,en;q=0.9,es-US;q=0.8,es;q=0.7,ar-JO;q=0.6,ar;q=0.5
(My APPID is fake in all these examples, so the request won't work by just copying and pasting what I have)
It's a pretty "catchy" bug - you are missing http:// in front of your url, so:
fetch('https://api.openweathermap.org/data/2.5/weather?q=Milwaukee&APPID=1234567890')
Since you've missed it, url is resolved to this (you can see it in your Network tab):
http://localhost:3000/api.openweathermap.org/data/2.5/weather?q=Milwaukee&APPID=1234567890
I have server running on localhost:8080 (localhost:3000 request is redirected to localhost:8080 by proxy definition in package.json) and sending requests from ReactJS app to this server on localhost. In all browsers suddenlly started occuring this problem. Requests (except keepalive request and 1 or 2 others) return 400 but does not reach server at all. E. g. in Chrome it is happening for all requests but in Firefox a few requests return status code 200 and response with data without problem but other requests behave as mentioned above.
I am using Windows 10.
All browsers have problems: Chrome, Firefox, IE, Edge, Opera, Chromium
I tried turning off defender firewall and AVG.
Request examples:
Chrome
Request URL: http://localhost:3000/api/essp/database?pageSize=1000
Request Method: GET
Status Code: 400 Bad Request
Request Headers:
Accept: */*
Accept-Encoding: gzip, deflate, br
Accept-Language: cs-CZ,cs;q=0.9
authorization: Bearer (token hidden for privacy reasons)
authorizationjwt: Bearer (token hidden for privacy reasons)
Connection: keep-alive
content-type: application/json
Cookie: _ga=GA1.1.1056630521.1566899267
Host: localhost:3000
Referer: http://localhost:3000/systematic-evidence
Sec-Fetch-Mode: cors
Sec-Fetch-Site: same-origin
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.132 Safari/537.36
Same request but in Firefox
Request URL: http://localhost:3000/api/essp/database?pageSize=1000
Request Method: GET
Status Code: 200 OK
Request Headers:
Accept
*/*
Accept-Encoding
gzip, deflate
Accept-Language
cs,sk;q=0.8,en-US;q=0.5,en;q=0.3
Authorization
Bearer (token hidden for privacy reasons)
Authorizationjwt
Bearer (token hidden for privacy reasons)
Connection
keep-alive
Content-Type
application/json
Cookie
_ga=GA1.1.647499021.1563197779
Host
localhost:3000
Referer
http://localhost:3000/systematic-evidence
User-Agent
Mozilla/5.0 (Windows NT 10.0; …) Gecko/20100101 Firefox/68.0
Different request in Firefox (400 is returned also in Chrome for this request)
Request URL: http://localhost:3000/api/essp/database/136adc97-75f7-4235-a48f-32e01c0f6add
Request Method: GET
Status Code: 400 Bad Request
Request Headers:
Accept
*/*
Accept-Encoding
gzip, deflate
Accept-Language
cs,sk;q=0.8,en-US;q=0.5,en;q=0.3
Authorization
Bearer (token hidden for privacy reasons)
Authorizationjwt
Bearer (token hidden for privacy reasons)
Connection
keep-alive
Content-Type
application/json
Cookie
_ga=GA1.1.647499021.1563197779
Host
localhost:3000
Referer
http://localhost:3000/systemat…97-75f7-4235-a48f-32e01c0f6add
User-Agent
Mozilla/5.0 (Windows NT 10.0; …) Gecko/20100101 Firefox/68.0
I am not BE developer but I was told it is not problem on server (on localhost), it is just something in my computer.
What could be causing this problem? Could it be something in Windows or some application intervenes to requests and returns 400 without reaching server? How am I able to find out or solve this problem?
Thanks for any helpfull answer
EDIT:
Not CORS problem because requests returning 400 are not reaching server at all. And also some non-simple requests return 200 without problem in few browsers (e. g. Firefox).
SOLUTION:
Solved by restoring Windows to factory settings.
I'm writing the client-side of an app with ReactJS, I'm stuck at getting data from a certain api. I get "No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access" error.
As I suppose the server is missing the "Access-Control-Allow-Origin" headers in order to enable CORS but what I don't understand is why when I'm trying to make an AJAX call with "Restlet Client - REST API testing" browser extension it actually works. I get a following success response. But It doesn't work inside my actual React Request. Is there a way I can to get rid of this error without any changes on the server side? Why does this extension actually work?
Connection: keep-alive
Content-Type: application/json; charset=UTF-8;
Date:
2017 Sep 22 22:45:40-1m 50s
Server: ..../1.6.2
Transfer-Encoding: chunked
Accept: */*
Accept-Encoding: gzip, deflate, br
Accept-Language: ru-RU,ru;q=0.8,en-US;q=0.6,en;q=0.4
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36
(KHTML, like Gecko) Chrome/60.0.3112.113 Safari/537.36
My React code but nothing special in there, just testing if I'm getting a response
componentWillMount() {
const url = "https://myserver.ru/api/issue?perPage=10";
Request.get(url).then((response) => {
this.setState({
issues: response
});
});
}
If you are making a cross-site requests then browser will expect Access-Control-Allow-Origin headers from the server. The value of that header can be,
Access-Control-Allow-Origin: *
or
Access-Control-Allow-Origin: http://localhost:3000
When you are requesting from localhost, make sure it also need to add port number as well.
More about CORS documentation:
https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS
Hope it helps.
I have zuul server implemented which does the routing to all my microservices. I have a seperate UI project which is in angular. I am trying to make an AJAX call from the UI app to a specific microservices which routes through Zuul but I am getting this error.
XMLHttpRequest cannot load http://localhost:8006/user/v1/userassociations. 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:63342' is therefore not allowed access. The response had HTTP status code 403.
But When I directly try to hit the api in local host which is hosted at http://localhost:4444/user/v1/userassociations it works perfectly fine. I have the below CORS configuration added to the actual api.
#Override
public void addCorsMappings(final CorsRegistry registry) {
registry.addMapping("/**").allowedMethods("PUT", "GET", "DELETE", "OPTIONS", "PATCH", "POST");
}
The problem is only happening when i try to hit the api via zuul I tried to add the same configuration to Zuul but it is not working.
I know it is the same origin issue but there must be a solution our microservices are suppose to go public so anyone can make the request from any domain.
Below is the Working AJAX call:- if i change the url to http://localhost:8006/user/v1/userassociations which is via zuul i get the cross origin.
var service = {};
service.userContextCall = function()
{
return $http({
url:'http://localhost:4444/user/v1/userassociations',
method: 'GET',
headers: {'Content-Type':'application/json',
'userContextId':'1234567890123456'}
}).success(function(response){
return response;
}).error(function(error){
return error;
});
};
return service;
Header that Iam receiving for when i hit the api via Zuul.
Request URL:http://localhost:8006/user/v1/userassociations
Request Method:OPTIONS
Status Code:403 Forbidden
Remote Address:[::1]:8006
Response Headers
view source
Allow:GET, HEAD, POST, PUT, DELETE, TRACE, OPTIONS, PATCH
Content-Length:20
Date:Tue, 23 Feb 2016 18:51:15 GMT
Server:Apache-Coyote/1.1
X-Application-Context:apigateway:8006
Request Headers
view source
Accept:*/*
Accept-Encoding:gzip, deflate, sdch
Accept-Language:en-US,en;q=0.8
Access-Control-Request-Headers:accept, usercontextid
Access-Control-Request-Method:GET
Connection:keep-alive
Host:localhost:8006
Origin:http://localhost:63342
Referer:http://localhost:63342/icpAccountHolder/app/index.html
User-Agent:Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/48.0.2564.116 Safari/537.36
Header when i direclty hit the api the working one.
Request URL:http://localhost:4444/user/v1/userassociations
Request Method:GET
Status Code:200 OK
Remote Address:[::1]:4444
Response Headers
view source
Access-Control-Allow-Credentials:true
Access-Control-Allow-Origin:http://localhost:63342
Content-Type:application/json;charset=utf-8
Date:Tue, 23 Feb 2016 18:54:19 GMT
Server:Apache-Coyote/1.1
Transfer-Encoding:chunked
Vary:Origin
X-Application-Context:userassociations-v1
Request Headers
view source
Accept:application/json, text/plain, */*
Accept-Encoding:gzip, deflate, sdch
Accept-Language:en-US,en;q=0.8
Connection:keep-alive
Host:localhost:4444
Origin:http://localhost:63342
Referer:http://localhost:63342/icpAccountHolder/app/index.html
User-Agent:Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/48.0.2564.116 Safari/537.36
userContextId:1234567890123456
Can anyone help me with this.
The fix seems to be using the ANGEL.SR6 spring cloud version instead of BRIXTON. But In case you want to use Brixton this is what i wrote to override the CORS filter in Zuul.
#Bean
public CorsFilter corsFilter() {
final UrlBasedCorsConfigurationSource urlBasedCorsConfigurationSource= new UrlBasedCorsConfigurationSource();
final CorsConfiguration corsConfig = new CorsConfiguration();
corsConfig.setAllowCredentials(true);
corsConfig.addAllowedOrigin("*");
corsConfig.addAllowedHeader("*");
corsConfig.addAllowedMethod("OPTIONS");
corsConfig.addAllowedMethod("HEAD");
corsConfig.addAllowedMethod("GET");
corsConfig.addAllowedMethod("PUT");
corsConfig.addAllowedMethod("POST");
corsConfig.addAllowedMethod("DELETE");
corsConfig.addAllowedMethod("PATCH");
urlBasedCorsConfigurationSource.registerCorsConfiguration("/**", corsConfig);
return new CorsFilter(urlBasedCorsConfigurationSource);
}
Whenever I try to add custom Request headers to my $http request the headers does not show up in the Request, instead its comes under Access-Control-Request-Headers like Access-Control-Request-Headers:accept, testHeader
See below the output in chrome's network tab:
Request Headers:
OPTIONS /v/xyx/abc/query?q=SELECT%20duration%20FROM%20TimeTable HTTP/1.1
Host: example.com
Connection: keep-alive
Access-Control-Request-Method: GET
Origin: http://localhost
User-Agent: XXXXXXXX Chrome XXXXXXX
Access-Control-Request-Headers: accept, testHeader
Accept: */*
Referer: http://localhost/test/
Accept-Encoding: gzip, deflate, sdch
Accept-Language: en-US,en;q=0.8
Whereas,I am expecting something like:
Request Headers:
OPTIONS /v/xyx/abc/query?q=SELECT%20duration%20FROM%20TimeTable HTTP/1.1
Host: example.com
Connection: keep-alive
Access-Control-Request-Method: GET
Origin: http://localhost
User-Agent: XXXXXXXX Chrome XXXXXXX
Accept: application/json
testHeader: zdhfguwe87fg8378287efijb8
Referer: http://localhost/test/
Accept-Encoding: gzip, deflate, sdch
Accept-Language: en-US,en;q=0.8
How can I prevent this from happening and show the headers under Request header?
See the config of the $http service in Angularjs that I've followed:
//***TRIED BOTH OF THESE:
//***TRY#1 $http.get(url, {headers:{"Accept": "application/json", "testHeader": "zdhfguwe87fg8378287efijb8"}}).then(.......
//***TRY#2
$http({
method: 'GET',
url: url,
headers: {
"Accept": "application/json",
"testHeader": "zdhfguwe87fg8378287efijb8"
}
})
.then(
function(){
//success
console.log(arguments);
}, function(){
//fail
console.log(arguments);
});
This is expected behavior as part of the CORS-preflight, which is an OPTIONS request. Once this request succeeds, the actual GET request will be fired by the browser with the custom headers, because the server accepted them.
Only a limited set of headers is approved by default for CORS requests, therefore to add others (including your custom header), the CORS-preflight request needs to ask the server for permission with the Access-Control-Request-Headers HTTP header.
See: https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS#Preflighted_requests
It has bloody taken my 3 hours to search for the fxxking answer.
Basically it is simple, just let stupid server accept the custom header.
What I have done were adding these to .htaccess
<IfModule mod_headers.c>
Header add Access-Control-Allow-Origin "*"
Header add Access-Control-Allow-Methods "POST, GET, OPTIONS, DELETE, PUT"
Header add Access-Control-Allow-Headers "origin, x-requested-with, content-type, x-custom-header-here"
</IfModule>
Now it allows server(API) to accept ajax request from everywhere with most methods and whatever your custom header is or headers are.
it will erase error msg of 'Request header field content-type is not allowed by Access-Control-Allow-Headers in preflight response.'
fxxking all these stupid rule makers!