I am calling the Rest call using the Ajax post method but i get the below error or response.
{"readyState":0,"status":0,"statusText":"error"}
Even i enable the cors($.support.cors = true; ) and crossDomain (crossDomain: true (add in headers)).
Here is the sample request:-
function() {
$.support.cors = true;
var evergentData = {
"UpdateContactRequestMessage":{
"channelPartnerID":"123456",
"email":"greg#gmail.com",
"firstName":"greg",
"lastName":"chappel",
"externalId":"GC123",
"sessionToken":"f53095854bb230996f54fe32ed5a63f68c7718c7"
}
};
//GetProducts();
jQuery.ajax({
type: 'POST',
url: 'url for rest api call',
contentType: "application/json",
Accept: "application/json; charset=utf-8",
dataType: 'json',
data: evergentData,
//data: JSON.stringify(evergentData),
crossDomain: true,
processData: true,
headers: { 'access-control-allow-origin': '*',
},
success: function(resp){
// we have the response
alert("Server said123:\n '" + resp + "'");
},
error: function(e){
alert('Error121212: ' + e);
alert(e.toString());
console.log('my message' + e);
console.log('tables: ' + JSON.stringify(e));
}
});
};
But i tested this Restapi call in the 'postman' google chrome extension i got the response(successfully got the response).
Here is the response headers:-
access-control-allow-headers → client_type, content-type, accept, accept-language, auth_token_base64, appID, accept-encoding, content-length, x-requested-with
access-control-allow-methods → POST, GET, OPTIONS, DELETE
access-control-allow-origin → *
allow → GET, HEAD, POST, PUT, DELETE, TRACE, OPTIONS
content-length → 92
content-type → application/json
x-frame-options → sameorigin
x-webobjects-loadaverage → 0
Anyone help me why i didn't get response from rest api call in JqueryAjax post calls.
Thank's advance.
It is important to understand that access-control-allow-origin': '*' in REQUEST header does nothing.
The Access-Control-Allow-Origin header must be in the RESPONSE header of the service you are calling. So the service regulates who is allowed to call the resource, thus service must add your app URL to it's RESPONSE Access-Control-Allow-Origin header.
Also note that wildcard * does not work for resources accessed over HTTPS. For resources over HTTPS ONLY absolute paths are valid.
Why Postman works? Cause it ignores the headers and policies while browser does not.
More reading:
https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS
Related
I searched a lot on the Internet, but I didn't find anything helpful for my problem.
I have a java server and a react client. My server is using jwt for authentication and returns a token to my client.
When I try to send data with a post method, my client does not send the headers, so my server returns an "Unauthorized" message. I tried to send the same request from Postman and ARC(Advanced Rest Client) and it works.
Here is my client code:
fetch(url, {
method: 'POST',
crossDomain: true,
mode: 'no-cors',
body: JSON.stringify(data),
headers: {
'Authorization': 'Bearer ' + 'token generated from fiddler after running auth',
'Accept': 'application/json',
'Content-Type': 'application/json'
}
})
.then(response => response.json())
.then(responseJson => {
console.log(responseJson);
});
I tried using axios too and I have the same problem.
Also my server has #CrossOrigin(origins = {"*"}) annotation in all controller classes.
I don't know if my problem is with the client or with the server and why is working using Postman and ARC.
You are using mode: no-cors which basically strips out all headers which are not simple headers: https://developer.mozilla.org/en-US/docs/Web/API/Request/mode
You should enable CORS and allow your domain on the server.
When trying to issue a POST request in firefox the following error messages come up:
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://example.net/graphql. (Reason: missing token 'content-type' in CORS header 'Access-Control-Allow-Headers' from CORS preflight channel).
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://example.net/graphql. (Reason: CORS request did not succeed).
The same request succeeds in Chrome. The request I am sending is:
method: 'POST',
headers:{
'x-client-id': '123',
'content-type': 'application/json; charset=UTF-8'
},
body: JSON.stringify({
query: "query ..."
})
})
.then(res => res.json())
.then(console.log);```
I am issuing this request while on another https origin.
My setup in my code for cors is simply the spring annotation:
```#CrossOrigin(allowedHeaders = {"content-type", "x-client-id"})```
You will need these headers:
Access-Control-Allow-Origin: http://api.bob.com
Access-Control-Allow-Methods: GET, POST, PUT
Access-Control-Allow-Headers: X-Custom-Header Content-Type: text/html;
charset=utf-8
at the target in order to allow CORS. If you have no access to the remote stuff, then use your server as a proxy and send the request from there, return the response to your browser.
I want to call my rest web service from ajax. Url for my service is 'https://scv-dev.com/cdcAug/surveys/surveyData'. Iam able to call this service from rest client (firefox browser) but when am trying to call from ajax am getting error.
Ajax call :
$.ajax({
type: "POST",
url: "https://scv-dev.com/cdcAug/surveys/surveyData",
data: JSON.stringify({surveyId:1}),
dataType: "json",
headers: {
Accept: "application/json",
"Access-Control-Allow-Origin": "*"
},
success: function (data) {
alert(1);
},
error: function (jqXHR) {
alert(2);
}
});
Below is code for webs service :
#RequestMapping(value = "/surveyData", method = RequestMethod.POST, headers = "Accept=application/json")
public #ResponseBody
SurveyDataResponse getSurveyData(#RequestBody SurveyResApp surveyResApp,
final HttpServletResponse httpResponse) {
..............
}
You appear to be confused about Access-Control-Allow-Origin: *. That is something the server returns, not something the client sets.
It appears that you have a same-origin access error and looking in the browser error log or diagnosing the returned error codes should tell you what exactly is going on.
You probably need to enable your web service for cross origin access by adding that header Access-Control-Allow-Origin: * to your server response. See here for an example.
I created filter class added below code in that to add "Access-Control-Allow-Methods" in response.
response.addHeader("Access-Control-Allow-Origin", "*");
response.addHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE, HEAD");
response.addHeader("Access-Control-Allow-Headers", "X-PINGOTHER, Origin, X-Requested-With, Content-Type, Accept");
response.addHeader("Access-Control-Max-Age", "1728000");
I am new to webservice and ajax .. I tried to call a webservice using POST method.
I tried to invoke it using Postman (Google chrome App) and I was getting the response but when I tried using Ajax I am getting error
Following are the things I did:
My Code: (I wrote a JS in which I included following code and tried all the commented options too ):
$.ajax({
crossDomain: true,
url : 'https://yxyxyxyxyx/search/v1/query.json',
type : 'POST',
dataType : "json",
data: {appId: "a9b475a079",query: "dhcp"},
//async : true,
//headers: {"Content-type": "application/json"},
headers: { 'Access-Control-Allow-Origin': '*' },
//contentType: "application/json; charset=utf-8",
//headers: ('Access-Control-Allow-Methods: GET, POST, OPTIONS'),
//headers: ('Access-Control-Allow-Headers: Origin, Content-Type, Accept, Authorization, X-Request-With'),
//headers: ('Access-Control-Allow-Credentials: true'),
// Access-Control-Allow-Origin: "http://localhost:8080",
// headers: { 'Access-Control-Allow-Origin': '*' },
//userAgent : 'Mozilla/22.0',
success: function(data){
alert("hi success");
},
error: function(data) {alert("An error occured: " + data.status + " " + data.statusText);
});
I am getting the alert in the error and getting following error while debugging:
XMLHttpRequest cannot load https://www.sample.search/v1/query.json. The request was redirected to 'https://www.sample/obrareq.cgi?wh%3DCCI-STG4%20wu%3D%2Fuesps%…n-tools-stage.cisco.com%20ru%3D%252Fuesps%252Fsearch%252Fv1%252Fquery.json', which is disallowed for cross-origin requests that require preflight.
I tried all the options to resolve the CROS option in which I found on net… do we have any other way to resolve it.
Can someone help me if we can do it using a java class that will also serve the purpose
I have a restlet resource that authenticates a person and sets a cookie with a key:
#Post("json")
public Representation login(String json) {
// validate user credentials ...
getResponse().getCookieSettings().add(new CookieSetting(1, "k", key));
getResponse().getCookieSettings().add(new CookieSetting(1, "p", person.getURI()));
return new StringRepresentation(response.toString(), MediaType.APPLICATION_JSON);
}
When I invoke the URL associated with the login() method, everything seems to be fine. The cookies seem to be returned correctly in the response, and if I already have received cookies before, they are sent to the server:
Remote Address: 127.0.0.1:8000
Request URL: http://127.0.0.1:8000/api/person
Request Method: POST
Status Code: 200 OK
Request Headers
Accept: undefined
Accept-Encoding: gzip,deflate,sdch
Accept-Language: en-US,en;q=0.8,pt-PT;q=0.6,pt;q=0.4,es-419;q=0.2,es;q=0.2,en-GB;q=0.2
Connection: keep-alive
Content-Length: 42
Content-Type: application/json
Cookie: k="546f71445bf1bacd60a3f715d0250267"; p="http://compflow.pt/flowOntology/admin"
Host: 127.0.0.1:8000
Origin: http://127.0.0.1:8000
Referer: http://127.0.0.1:8000/job
X-Requested-With: XMLHttpRequest
Response Headers
Accept-Ranges: bytes
Content-Length: 46
Content-Type: application/json; charset=UTF-8
Date: Tue, 01 Jul 2014 15:05:13 GMT
Server: Restlet-Framework/2.1.7
Set-Cookie: k=546f71445bf1bacd60a3f715d0250267
Set-Cookie: p=http://compflow.pt/flowOntology/admin
Vary: Accept-Charset, Accept-Encoding, Accept-Language, Accept
The invocation to http://127.0.0.1:8000/api/person is performed through an AJAX call using JQuery as follows:
$.ajax({
url: '/api/person',
type:'POST',
accepts : "application/json",
contentType : "application/json",
processData : false,
dataType : "text",
data: JSON.stringify(data),
success: function (data) {
data = JSON.parse(data);
sessionStorage["userData"] = JSON.stringify(data.data);
if(callback) callback();
},
error: function(data) {
$('.alert-error').text(data).show();
}
});
However, if I try to perform a GET (directly through the browser) to the address http://127.0.0.1:8000/job, the cookies are not sent. The Cookie header is not set in the request.
Since it is not a cross-domain request and no restrictions are set regarding the path and domain of the cookies (I have tried setting them to "/" and "127.0.0.1" to no avail), I have no ideas left regarding what may be causing this issue. I would greatly appreciate all the help you can give me.
Curiously, the kind of HTTP server connector changes the behavior of the code. I've entered an issue for that (https://github.com/restlet/restlet-framework-java/issues/927).
As a workaround, I suggest you to precise the path, as follow:
getCookieSettings().add(new CookieSetting(0, "k", key, "/", null));
NB: inside a ServerResource; you can use the shortcut "getCookieSettings()", instead of "getResponse().getCookieSettings()".