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.
Related
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));
}'
i'm trying to build http adapter with token authorization form ajax request but get 401 error
Status Code:strong text
401 Unauthorized
missing_authorization
$.ajax({
type: "POST",
url: "https://abcd",
data: JSON.stringify({ "template": 1 }),
headers: { "Authorization": "xxxx", "Accept": "application/json",
"Content-Type": "application/json" }
});
function My_adapter() {
path = '/xxx';
var input = {
method : 'post',
path : path,
returnedContentType : 'json',
headers: {'Content-type':'application/json',
'Accept':'application/json', 'Authorization':'Token XXXXX'},
parameters: JSON.stringify({ "template": 1 }),
};
var result=WL.Server.invokeHttp(input);
return result;
}
tnx for your help,
sahar
The error message you see is expected. The client side code you posted shows that you are attempting to invoke MFP server outside of MFP client SDK ( jQuery ajax call). This call does not carry all the required information to the server and server sends the "missing_authorization" message as a result.
If you wish to invoke an adapter, use WLResourceRequest API provided by MFP client SDK. This takes care of handling the authentication handshake with MFP server. More details on the API usage here.
I want to post a JSON object from my page to a Rest WS. But when I am posting json through jQuery ajax call as output I am getting a HTML page with "HTTP Status 405 - Method Not Allowed" instate of JSON, which I am sending from Rest Web Service. Please refer the following code snippet.
I am using jquery 1.11.3 version.
http://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js
jQuery Ajax Call:
$.ajax({
url: "http://localhost:8080/MyWebService/api/myService/jsonpost",
method: "POST",
data: jsonObj,
dataType: 'application/json',
contentType: "application/json",
success: function(result){
alert(result);
},
error(){
console.log('Error');
}
});
Please note my rest web service is running in my local tomcat.
Please find my Rest Web Service POST code.
#POST
#Path("/jsonpost")
#Consumes(MediaType.APPLICATION_JSON)
#Produces(MediaType.APPLICATION_JSON)
public String crunchifyJsonPostREST(SampleVO input) throws JSONException{
SampleVO sampleVO = input;
return new Gson().toJson(sampleVO);
}
VO:
public class SampleVO {
private String name;
/**
* #return the name
*/
#XmlElement
public String getName() {
return name;
}
/**
* #param name the name to set
*/
public void setName(String name) {
this.name = name;
}
}
My Maven Dependency is:
<dependency>
<groupId>com.sun.jersey</groupId>
<artifactId>jersey-server</artifactId>
<version>1.8</version>
</dependency>
<dependency>
<groupId>com.sun.jersey</groupId>
<artifactId>jersey-json</artifactId>
<version>1.8</version>
</dependency>
Firebug Details:
Please find my ajax request Header.
Please find my ajax response and response HTML.
Need your help to resolve this issue.
Thanks is advance.
Solution:
After lot of googling I have found some solution. Now I am using HTTP-Proxy-Servlet.
I have crated a java web application with my html page which has the ajax call and from my ajax call I am calling a URL of same domain. Please refer my ajax call.
$.ajax({
url: "rest/api/crunchifyService/jsonpost",
method: "POST",
data: JSON.stringify(jsonObj),
dataType: 'json',
contentType: "application/json",
success: function(result,status,jqXHR ){
//Do something
},
error(jqXHR, textStatus, errorThrown){
//Do something
}
});
Now I have done this same domain call mapping with org.mitre.dsmiley.httpproxy.ProxyServlet. Please refer my web xml.
<servlet>
<servlet-name>proxy</servlet-name>
<servlet-class>org.mitre.dsmiley.httpproxy.ProxyServlet</servlet-class>
<init-param>
<param-name>targetUri</param-name>
<param-value><!-- Cross domain URL goes here --></param-value>
</init-param>
<init-param>
<param-name>log</param-name>
<param-value>true</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>proxy</servlet-name>
<url-pattern>/rest/*</url-pattern>
</servlet-mapping>
Now my ajax is calling this Proxy Servlet and it is redirecting to the CROS destination Rest Web Service.
Please refer the following URL, you will get more details.
https://github.com/mitre/HTTP-Proxy-Servlet
After lot of googling I have found some solution. Now I am using HTTP-Proxy-Servlet.
I have crated a java web application with my html page which has the ajax call and from my ajax call I am calling a URL of same domain. Please refer my ajax call.
$.ajax({
url: "rest/api/crunchifyService/jsonpost",
method: "POST",
data: JSON.stringify(jsonObj),
dataType: 'json',
contentType: "application/json",
success: function(result,status,jqXHR ){
//Do something
},
error(jqXHR, textStatus, errorThrown){
//Do something
}
});
Now I have done this same domain call mapping with org.mitre.dsmiley.httpproxy.ProxyServlet. Please refer my web xml.
<servlet>
<servlet-name>proxy</servlet-name>
<servlet-class>org.mitre.dsmiley.httpproxy.ProxyServlet</servlet-class>
<init-param>
<param-name>targetUri</param-name>
<param-value><!-- Cross domain URL goes here --></param-value>
</init-param>
<init-param>
<param-name>log</param-name>
<param-value>true</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>proxy</servlet-name>
<url-pattern>/rest/*</url-pattern>
</servlet-mapping>
Now my ajax is calling this Proxy Servlet and it is redirecting to the CROS destination Rest Web Service.
Please refer the following URL, you will get more details.
https://github.com/mitre/HTTP-Proxy-Servlet
datatype should be dataType: 'json'
If you are using contentType: "application/json", , then you should stringify your data.
data:JSON.stringify(jsonObj),
Try using type & contentType settings of ajax:
type:'POST',
contentType: 'application/json',
Example:
function loadDoc(){
var num = '{"empid": 45,"name": "gaurav","salary":566.55}';
$.ajax({
url: 'http://localhost:9029/addS',
method: 'POST',
type:'POST',
contentType: 'application/json',
success: function(response){
console.log("response::::"+response);
$("#output").text(response);
},
error: function( jqXHR,textStatus, errorThrown){
console.log("Error askdjk");
console.log(jqXHR);
console.log(textStatus);
console.log(errorThrown);
}
});
}
I am building a web app and for the server I am using nodejs and express. When I make a request to the server just from the browser it works fine, but when I try an ajax request from the client it registers on the server, but gives me an error on the client. Here is what I am using for the ajax request:
$.ajax({
async: false,
dataType: "json",
url: url,
crossDomain: true,
success: function(response) {},
error: function(response){
alert(JSON.stringify(response));
}
});
on server side, when you send the request... set header of response to allow cors:
something like this >>
res.writeHead(200,{
'Access-Control-Allow-Origin' : '*'
});
In place of '*', you can specify a set of urls, you want to server response to...
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.