While sending a post request from my tomcat web service i got an error as below:
" Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access."
I'm using tomcat 9.* and developed my web service with jax-rs java web api.
While i have tested my web service with postman, i got a good response from my web service (http 200 response). Yet, when i tried to send ajax post request i got the message above. I tried to enable the CORS filter and tried to send get request that working fine..
the web.xml:
<filter>
<filter-name>CorsFilter</filter-name>
<filter-class>org.apache.catalina.filters.CorsFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>CorsFilter</filter-name>
<url-pattern>/*</url-pattern>
<dispatcher>FORWARD</dispatcher>
</filter-mapping>'
the jax-rs post function:
#POST
#Path("/users2")
#Consumes("application/json")
#Produces(MediaType.APPLICATION_JSON)
public Response SetAllTlcsStatus(List<TrafficLight> c){
System.out.println("You have entered the SetTlc function");
return Response.ok() //200
.header("Access-Control-Allow-Origin", "*")
.header("Access-Control-Allow-Methods", "GET, POST, DELETE,
PUT")
.allow("OPTIONS").build();
}
the ajax request:
$.ajax({
type : "POST",
url : "http://localhost:8080/userManagement/rest/Traffic/users2",
contentType :"application/json; charSet=UTF-8",
data : d,
dataType : "json",
beforeSend: function (xhr){
console.log('Before');
xhr.setRequestHeader('Authorization', make_base_auth(user, pass));
}'
You say "I tried to enable the CORS filter and tried to send get request that working fine."
Do you mean that GET method works but POST not? If so you must allow it on your REST service/terminal and also these settings
header("Access-Control-Allow-Origin", "*")
header("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT")
Finally, if by any chance your AJAX still returns failed try
$.ajax({
type : "POST",
url : "http://localhost:8080/userManagement/rest/Traffic/users2",
contentType :"application/json; charSet=UTF-8",
data : d,
dataType : "json",
**xhrFields: {
withCredentials: true
},
crossDomain: true,**
beforeSend: function (xhr){
console.log('Before');
xhr.setRequestHeader('Authorization', make_base_auth(user, pass));
}'
Related
I am creating a client side session using cross domain ajax call to Spotfire server. For authentication I am using basic authentication method. When I make my request through Postman with Authorization header and value 'Basic ' + btoa('user:password') it send correct header and start a new session, whereas in web browser it shows error as
NetworkError: 405 Method Not Allowed -
http://server-path/GetJavaScriptApi.ashx?Version=8.0
&
Cross-Origin Request Blocked: The Same Origin Policy disallows reading
the remote resource at
http://server-path/GetJavaScriptApi.ashx?Version=8.0.
(Reason: CORS header ‘Access-Control-Allow-Origin’ missing).
This was because in cross domain ajax call first OPTIONS request is made followed by POST/GET, to overcome this I made dataType: "jsonp" in my ajax call. Now GET calls are working but now gives me a new error:
The resource from
“http://server-path/GetJavaScriptApi.ashx?Version=8.0&callback=jQuery111107482621169238032_1487159470493&_=1487159470494”
was blocked due to MIME type mismatch (X-Content-Type-Options:
nosniff).
Ajax code is as follows:
$.ajax({
url: 'https://server-path/GetJavaScriptApi.ashx?Version=8.0',
type: 'GET',
crossDomain: true,
beforeSend: function(xhr) {
xhr.setRequestHeader("Authorization", Basic ' + btoa('user:password'));
xhr.setRequestHeader("content-type", 'text/plain');
xhr.setRequestHeader("X-Content-Type-Options", "nosniff");
},
dataType: "jsonp",
success: function (jsonData) {
console.log(jsonData);
},
});
Call to https://server-path/GetJavaScriptApi.ashx?Version=8.0 return javascipt as response after successful authentication
Please help to resolve.. Thanks
I have two servers:
Server 1 (URL: https://server1.AAA.com) and
Server 2 (URL: https://server2.AAA.com)
In Server 1 JSP page, I try to use ajax to send a POST request to Server 2.
$.ajax({
type: "POST",
url: "https://server2.AAA.com/servlet",
data: 'test',
success: function(data, textSuccess) {
alert(data);
}
error: function(xhr, status, error) {
alert('error');
},
});
In Server 2, I checked that it has received the request from Server 1, and I tried to response the following message:
doPost(...) {
response.addHeader("Access-Control-Allow-Origin", "*");
response.getwriter().write("success");
}
However, I found that Server 1 cannot receive the response data from Server 2, it went to the error alert. I have totally no idea why such a situation happened. I have already set response header for all origins, and did set the security constraint in my application's web.xml:
<security-constraint>
<web-resource-collection>
<web-resource-name>test</web-resource-name>
<url-pattern>/*</url-pattern>
<http-method>POST</http-method>
</web-resource-collection>
</security-constraint>
Please tell me what I am still missing / what should I check.
I'm working with CodeIgniter2 Rest API and AJAX to make requests from a smartphone with PhoneGap to a AWS server with apache.
Everything was working fine when working on my localhost/browser.
But when trying to set up a distant server things got bad.
I have configured my server properly with CORS so that it allows external requests as explained here :
http://dev.nuclearrooster.com/2011/01/03/cors-with-apache-mod_headers-and-htaccess/
To secure the API, I have been setting up an API KEY that I have to pass in the header of my request like so:
$.ajax({
type:"GET",
url: server_url + 'user/available',
headers: { 'X-API-KEY': key },
dataType: 'json'
});
But then, after seeing my ajax called being refused because of an invalid API Key, I have been trying to make sure the server received the key. and it doesnt. when I try to echo my key, its empty.
I can see in my debug console the following:
Request header field X-API-KEY is not allowed by Access-Control-Allow-Headers.
So I have been modifying my .htaccess following this post:
Header add Access-Control-Allow-Origin "*"
Header add Access-Control-Allow-Headers "origin, x-requested-with, content-type, x-api-key"
Header add Access-Control-Allow-Methods "PUT, GET, POST, DELETE, OPTIONS"
so now, the message is gone but the problem still remains the same ... why ?
How can I transmit this X-API-KEY through my AJAX call Header so I can authentificate my users ?
Many Thanks
I faced this problem and with weeks of tweaking I was able to get it to work with a hack of a job... I can't remember the exact part that did fix it but will provide with what I am currently using.
Server Side
function __construct(){
parent::__construct();
header("Access-Control-Allow-Origin: " . $_SERVER['HTTP_ORIGIN']);
header("Access-Control-Allow-Credentials: true");
header("Access-Control-Allow-Methods: GET, POST, OPTIONS");
// Access-Control headers are received during OPTIONS requests
if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
header("Access-Control-Allow-Headers: X-API-KEY");
}
function available_options(){
$this->response(array('response' => array()), 200);
}
Client Side
function sendData(dataToSend, successCallback) {
window.default_headers['X-API-KEY'] = '_KEY_';
return $.ajax({
type: "POST",
url: server_url + 'user/available',
data: { data : JSON.stringify(dataToSend) }, // serializes the form's elements.
dataType: 'json',
headers: window.default_headers,
xhrFields: {
withCredentials: true
}
});
}
Since you're using a GET request, possibly using JSONP would be of more use, this avoids cross domain requests.
JSONP Request
$.ajax({
type : "GET",
dataType : "jsonp",
url: server_url + "user/available?callback=?", // ?callback=?
success: function(data){
// do stuff with data
}
});
I have this webapp where I make a post request using Ajax from Domain A to a rest service on Domain B
Domain B has been set up to serve the response with the CORS Access-Control* headers in order to get the cross-domain posting to work
Headers in response from domain B:
Access-Control-Allow-Credentials: true
Access-Control-Allow-Headers: content-type
Access-Control-Allow-Methods: POST GET OPTIONS
Access-Control-Allow-Origin: https://sub.domain-a.com
Access-Control-Max-Age: 180
The Ajax code
$.ajax({
url: 'https://sub.domain-b.com',
type: 'POST',
contentType: 'application/json',
headers: {
'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8'
},
data: json,
dataType: 'json',
xhrFields: {
withCredentials: true
},
success: function (data) {
},
error: function (jqXHR, textStatus, errorThrown) {
}
});
I am logged in on both domains and my request sends the necessary cookie (withCredentials=true), but I am still getting a 403 Forbidden from the response
Both domains are using SSL a certificate
I am beginning to wonder if the SSL's are causing the problem as this worked before and I am getting nothing in my logs
Are there anyone here that have any experience with something similar?
Any pointers?
It could be something similar to this issue:
Pre-flight OPTIONS request failing over HTTPS
Typically when the issue is with SSL and the preflight request though you wouldn't get back a 403, you'd just get the OPTIONS request aborting.
How does the service authenticate and authorise? Are you using self-signed certificates? It sounds like you're correct in thinking that SSL is causing the issue and without more info it's hard to say what your specific problem is.
I am making an Ajax request to remote server and sending parameters as POST method.
But I am getting following response:
**"MLHttpRequest cannot load http://rasovai.com/mobilecontact1.php?_dc=1369189135731. Origin null is not allowed by Access-Control-Allow-Origin. "**
I read about this error and found out that it is because of CORS, so I add header to the request as follows:
Ext.Ajax.defaultHeaders = {
'Accept': 'application/json',
'Accept': 'Access-Control-Allow-Origin: *',
'Accept': 'Access-Control-Allow-Credentials: true',
'Accept': 'Access-Control-Allow-Methods: OPTIONS, GET, POST',
'Accept': 'Access-Control-Allow-Headers: Content-Type, Depth, User-Agent, X-File-Size, X-Requested-With, If-Modified-Since, X-File-Name, Cache-Control'
};
but still I am getting the same error in response.
I am able to hit the url on server, but not able to pass the parameters.
Can anyone help me in this regard?
Thanks
Ishan jain
Those headers need to be sent by the server, not the client.
If you are using Chrome browser you can use --disable-web-security flag to allow cross domain requests and if you are building this into app this will work fine. Have a look at this thread for more details : How to use json proxy to access remote services during development
If you want to pass the params to the server then you can do it as following.
Ext.Ajax.request({
url : serverURL,
jsonData : requestParams, // Object which encapsulates the request params
method : 'POST',
withCredentials: true,
useDefaultXhrHeader: false,
// List of header params can be sent as follows
headers : {
"Content-Type" : "application/json",
"Accept" : "application/json",
"Access-Control-Allow-Origin":"http://localhost:8080",
"Authorization":auth
},
username : 'mobiliser',
password : 'secret',
success : function(response) {
}
failure : function ()
{
}
As you said in your question that, the server is on a different domain, you may have to use JSONP request.
Let me know if you have any questions.
Thanks-
Gendaful