I'm setting encrypted username and password authorization in fron end and getting request header response bearer authorization from server. In ajax i'm getting to get that response header in safari correctly but in chrome and firefox its like a null. The problem only in chrome and firefox to get bearer token. How to fix that issues?
Ajax code,
$.ajax({
type:"POST",
url:url,
dataType: "json",
async:false,
headers:{
'Authorization':'Basic '+btoa(useremail+":"+password)
},
data:'{"datas"}',
success: function (data, status, request, xhr){
alert(request.getResponseHeader('Authorization'));
}
Note that as of jQuery 1.8 async option is deprecated.
As to why this probably happens:
During a CORS request, the getResponseHeader() method can only access
simple response headers. Simple response headers are defined as
follows:
Cache-Control
Content-Language
Content-Type
Expires
Last-Modified
Pragma
And as for the solution:
If you want clients to be able to access other headers, you have to
use the Access-Control-Expose-Headers header. The value of this header
is a comma-delimited list of response headers you want to expose to
the client.
Source: https://www.html5rocks.com/en/tutorials/cors/
With reference from this articel : http://osric.com/chris/accidental-developer/2014/08/using-getresponseheader-with-jquerys-ajax-method/
Try with done function as shown in the example in the article :
$.ajax({
type:"POST",
url:url,
dataType: "json",
async:false,
headers:{
'Authorization':'Basic '+btoa(useremail+":"+password)
},
data:'{"datas"}',
}).done(function (data, textStatus, xhr) {
console.log(xhr.getResponseHeader('Authorization'));
});
try this..
var settings = {
"crossDomain": true,
"url": url,
"method": "POST",
"headers": {
"content-type": "application/x-www-form-urlencoded",
"Authorization":"Basic "+btoa(useremail+":"+password)
},
"data": {
"name": "name"
}
}
$.ajax(settings).done(function (data,status, xhr) {
console.log("Authorization=> "+xhr.getResponseHeader('Authorization'));
});
Related
I used postman to test my web service. In the http response body, I find the WS's response.
When I test my call, in my web application, using ajax, I can not find the response anymore. The tab contains a message saying "This request has no response data available."
this is my ajax call:
$.ajax({
url: url,
method: "POST",
data: params,
success:function(response) {
console.log(response); // no console here!
console.log('response');
},
error:function(){
console.log("error");
}
});
Hi, Try like this.
In the ajax, you are passing params, it should contain something like action = get_pincodes.
while handling this, action = get_pincodes.
you must write echo json_encode($responce);exit;
EX:
if($_REQUEST['action'] != "" && $_REQUEST['action'] == 'get_pincodes'){
$responce = array();
$responce[] = "500113";
$responce[] = "500114"; // etc....
echo json_encode($responce);exit;
}
maybe Adding charset=utf-8 to Content-Type in the response headers could solve the issue : Content-Type: application/json; charset=utf-8
$.ajax({
url: url,
method: "POST",
dataType: "json",
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json;charset=utf-8'
},
data: params,
success:function(response) {
console.log(response); // no console here!
console.log('response');
},
error:function(){
console.log("error");
}
});
try to check if the XHR filter is selected and dont forget to reload the page afterwards
I have jquery ajax query:
var data2 = "data"
var ajaxOptions2 = {
type: "post",
url: "http://localhost:8050/adapter/interface",
data: data2,
dataType: "json",
success: onSuccess,
error: onError,
processData: false,
contentType: "application/json; charset=UTF-8"
};
$.ajax(ajaxOptions2);
and this post request is working properly
I tried to rewrote this to the angular2 http.post:
let bodyString = "data";
let headers = new Headers({ 'dataType': 'json', 'contentType': 'application/json; charset=UTF-8' });
let options = new RequestOptions({ headers: headers, method: RequestMethod.Post});
that.http.post(that.url, bodyString, options)
.map(that.extractData)
.catch(that.handleError)
.subscribe(data => { console.log("test")});
but http.post is returning error:
XMLHttpRequest cannot load http://localhost:8050/adapter/interface. Request header field dataType is not allowed by Access-Control-Allow-Headers in preflight response.
Can you tell why why jquery ajax is working but my http.post dont?
Well the problem is exactly what the error message is stating.
In your post request you are setting the header "dataType" which obviously isn't allowed by the server for the POST or OPTIONS request.
You are not setting this header in your ajax request.
If you want to make it work you either have to remove the header or re-configure your server in order to accept this header instead.
I want to call an OAuth2 service with grant_type password.
I am using Backbone with Jquery.
Parameters for the POST:
grant_type=password
client_id=[YOUR_APP_ID]
client_secret=[YOUR_CLIENT_SECRET]
username=[USER_NAME]
password=[USER_PASSWORD]
I have tried several NPM plugins but all give error.
I have created a custom post AJAX but this also does not work:
var results = $.ajax({
// The URL to process the request
url : "https://app1pub.smappee.net/dev/v1/oauth2/token",
type : "POST",
data : {
grant_type : "password",//jshint ignore:line
username: "myuser",
password: "secret",
client_id: "myclient",//jshint ignore:line
client_secret: "clientSecret"//jshint ignore:line
},
beforeSend: function (xhr) {
xhr.setRequestHeader("Authorization", "Bearer $token");
xhr.setRequestHeader("Access-Control-Allow-Origin", "*");
},
dataType: "json",
contentType: "application/x-www-form-urlencoded",
success: function(response) {
//console.log(response);
console.log(response.access_token);//jshint ignore:line
data.access_token = response.access_token;//jshint ignore:line
//tokenGranted();
}
});
return results.responseText;
(see fiddle: https://jsfiddle.net/gf70sss5/)
All give me the error:
"XMLHttpRequest cannot load https://app1pub.smappee.net/dev/v1/oauth2/token. 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:9000' is therefore not allowed access."
Does anyone know a NPM plugin which works with the password granttype? Preferrably with an example. I have tried a few (like simple-oauth2) but I can't get any working.
Or an AJAX call which does work? Or what I am doing wrong?
Try this, but i've still a problem with the "Access-Control-Allow-Origin" error
var url = 'https://app1pub.smappee.net/dev/v1/oauth2/token';
// ajax call
$.ajax({
type: "POST",
url: url,
data: {"grant_type": "password", "client_id": client_id, "client_secret": client_secret,"username": username,"password": password},
beforeSend : function(xhr) {
xhr.setRequestHeader("POST", "/dev/v1/oauth2/token HTTP/1.1");
xhr.setRequestHeader("HOST", "app1pub.smappee.net");
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
},
error : function() {
// error handler
},
success: function(data) {
// success handler
alert(data["access_token"])
}
With Chrome REST service I do this: a post to a certain url, I send a json string in the body, I set the content type as application/json and when I execute the post I get the proper answer.
I am trying to do the same post with jquery.
I first try with:
var beacon = {"beaconid.minor":2,"beaconid.UUID":"beaconnr","beaconid.major":1};
$.ajax({
type: "post",
data: JSON.stringify(beacon),
contentType: "application/json",
dataType: "jsonp",
crossDomain: true,
url: "myurl"}).done(function() {
alert("success");
}).fail(function()
{
alert("error");
});
by I seem to get no answer, I don't get the success alert nor the error alert.
I have then tried with:
var jqxhr = $.post( "myurl", {"beaconid.minor":2,"beaconid.UUID":"beaconnr","beaconid.major":1}).done(function(data, textStatus, jqXHR)
{
}).fail(function(jqXHR, textStatus, errorThrown)
{
alert(textStatus);
});
At least now I get an alert with the textStatus as an error. It is something...but not enough. I could I do a successful post?
The issue is you're setting dataType: "jsonp" for a POST request. JSONP doesn't support POST requests, only GET requests.
I suggest changing to dataType: "json" to see if the service supports CORS. If it doesn't then you'll have to do something like proxy the request through the local server, to get around CORS.
You should not be sending "post" as "type", rather as "method"
And like pointed above, the data type should be json and not jsonp.
$.ajax({
method: "post",
data: JSON.stringify(beacon),
contentType: "application/json",
dataType: "json",
url: "myurl"}).done(function(response) {
alert("success");
//if in chrome
//console.log(response);
}).fail(function(error)
{
//if using Chrome
//console.log(error);
alert(error);
});
I have the following jQuery AJAX request:
// collect form data and create user obj
var user = new User();
user.firstname = $("#usrFirstName").val();
user.lastname = $("#usrSurname").val();
user.role = $("#usrRole").val();
// actual ajax request
$.ajax({
type: 'POST',
url : 'http://awesome-url',
crossDomain: true,
data: user,
contentType:"application/json; charset=utf-8",
dataType: 'json'
}).done(function(data, status) {
alert(JSON.stringify(data));
}).fail(function(data, status) {
alert(status);
alert(JSON.stringify(data));
});
The response from the Server is:
"status":400,"statusText":"Bad Request"
"The request sent by the client was syntactically incorrect."
The server is running Spring-MVC. But as far as I can tell it is working correctly. Because if I'm sending a request manually with Postman and the following configuration it works.
Header:
Content-Type application/json; charset=utf-8
Content:
{"firstname":"alex","lastname":"lala","role":"admin"}
I have to mention that it is a cross-domain request (for the time developing, it will be hosted on the same domain as the server later). I did disable the security settings in the browser and AJAX requests to the server are working fine (as long as I don't have to send data).
you need to serialize your json, try:
$.ajax({
type: 'POST',
url : 'http://awesome-url',
crossDomain: true,
data: JSON.stringify(user),
contentType:'application/json; charset=utf-8',
dataType: 'json'
})
JSON.stringify() method is used to turn a javascript object into json string. You need to have this. In addition it is better to include success and error portions in the AJAX.
$.ajax({
type: 'POST',
url : 'http://awesome-url',
crossDomain: true,
data: JSON.stringify(user), // turn a javascript object into json string
contentType:'application/json; charset=utf-8',
dataType: 'json',
success: function (html) {
alert(html);
}, error: function (error) {
alert(error);
}
})