I seem to be getting a issue with Amazon Gateway API not liking my sent params for example.
$.ajax({
url: "https://tibqwxuqoh.execute-api.us-east-1.amazonaws.com/dev/getitems",
type: "POST",
data: {
"device": "test",
"datetime": "1446757400919"
},
success: function (returnhtml) {
console.log(returnhtml);
$("#result").append("DOES NOT WORK - <br>" + JSON.stringify(returnhtml));
}
});
$.ajax({
url: "https://tibqwxuqoh.execute-api.us-east-1.amazonaws.com/dev/getitems",
type: "POST",
data: {},
success: function (returnhtml) {
console.log(returnhtml);
$("#result").append("<br>WORKS ???? - <br>" + JSON.stringify(returnhtml));
}
});
Here is a working example.
http://jsfiddle.net/Uwcuz/4315/
Can someone let me know why it wont let me send params every time i add a parameter i get this error.
{
Type = User;
message = "Could not parse request body into json.";
}
OK THIS WORKS BUT SEEMS A BIT WEIRD TO ME.
$.ajax({
url: "https://tibqwxuqoh.execute-api.us-east-1.amazonaws.com/dev/getitems",
type: "POST",
data: "{\"device\": \"test\",\"datetime\": \"1446757444524\"}",
success: function (returnhtml) {
console.log(returnhtml);
$("#result").append("WORKS - <br>" + JSON.stringify(returnhtml));
}
});
The problem lies in how you send the data to API Gateway.
Without knowing the details of your API configuration I am guessing that you have a Request Mapping setup for application/json.
jQuery will by default post your data as application/x-www-form-urlencoded but you want to send it as json.
You can do this without having to fiddle too much with the data yourself:
var requestParams = {
url: "https://tibqwxuqoh.execute-api.us-east-1.amazonaws.com/dev/getitems",
method: "POST,
contentType: "application/json",
dataType: "json",
data: JSON.stringify({
"device": "test",
"datetime": "1446757400919"
});
};
var request = $.ajax(requestParams);
The key here is JSON.stringify() and telling jQuery that the dataType is json as well as setting the contentType to application/json.
Related
I have a postman collection and It's POST call and the request body is type of plain/text and I just want to automate this using cy.request but I'm not sure how to pass the test body in the cy.request body section and it returned 400 bad request if I run the below code.
cy.request({
url: `${url}/user`,
method: "POST",
headers: {
'Content-Type': 'plain/text'
},
body: {
"confirmEmail": "true"
}
}).then(res =>{
cy.task('log',"Email id "+res.body.emailAddress);
return res.body;
});
}
The above request return .json response but the input request if text format and the same working fine in the postman tool.
Passing the request body in the below format in the postman tool and its working fine.
confirmEmail=true
My assumption is in the request body our endpoint is expecting a boolean value, but you are passing a string. So changing "confirmEmail": "true" to "confirmEmail": true should work.
cy.request({
url: `${url}/user`,
method: 'POST',
headers: {
'Content-Type': 'plain/text',
},
body: {
confirmEmail: true,
},
}).then((res) => {
cy.log(res.body.emailAddress) //prints email address from response body
})
In case you need to pass parameters in your URL you can directly use qs
cy.request({
url: `${url}/user`,
method: 'POST',
qs: {
confirmEmail: true,
},
headers: {
'Content-Type': 'plain/text',
},
}).then((res) => {
cy.log(res.body.emailAddress) //prints email address from response body
})
I have the HTML file and try to send the request from that page with JavaScript or jQuery, but it doesn't send the "header" to the server and it gives me the error 405. I've read related questions and try out some of them but the error code was the same. I use Fiddler to see the final request and in that there is no header as well as the method change to the OPTION!
some of the codes I used:
$.ajax({
url: "URL",
type: "GET",
beforeSend: function(xhr){xhr.setRequestHeader('Authorization', 'Bearer HASHKEY');},
success: function() { alert('Success!'); }
});
or
var xhttp = new XMLHttpRequest();
xhttp.open("GET", "URL", true);
xhttp.setRequestHeader("Authorization", "Bearer HASHKEY");
xhttp.setRequestHeader('Content-Type', 'text/plain');
xhttp.setRequestHeader('Accept', 'application/json');
xhttp.send();
xhttp.onreadystatechange = function () {
var response = xhttp.responseText;
if (xhttp.readyState == 4 && xhttp.readyState == 200) {
var obj = JSON.parse(response);
// handle data as needed...
alert("obj" +obj);
}
};
Totally speaking I'm looking for a piece of code which can call API from the HTML which is content header: authorization.
Cheers
Try this:
$.ajax({
url: "URL",
type: "GET",
headers: {
"Authorization": "Bearer HASHKEY"
},
success: function() { alert('Success!'); }
});
Also, check that your server configuration supports CORS and explicitly allows the Authorization header.
I want to call a method from API Controller using AJAX. I have tried the following
I have added one hidden field in the view (like what we are doing in mvc controller)
<input type="hidden" id="GetShoppingCartUrl" value="#Html.Action("GetShoppingCartUrl","Cart")"/>
Then I have written ajax
function GetShoppingCart() {
debugger;
var url = $('#GetShoppingCartUrl').val();
$.ajax({
type: "get",
url: url,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
},
error: function () {
}
});
}
But here it is not getting the method, GetShoppingCartUrl from the API Controller CartController. I want to call that method, what changes make it happening ?
function GetShoppingCart() {
debugger;
var url = "Cart/GetShoppingCartUrl"
$.ajax({
type: "get",
url: url,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
},
error: function () {
}
});
}
you can directly put your actionlink in the url
Hope it helps. :)
Use this below code to get the url of your site in javascript and append it before the url in ajax call. e.g var url = baseUrl+ "Cart/GetShoppingCartUrl";
#{
string url = Request.Url.GetLeftPart(UriPartial.Authority) + Request.ApplicationPath;
if(url[url.Length-1]!='/')
{
url =url+ "/";
}
}
var baseUrl = '#url';
//alert(baseUrl);
I am using jq datatable, I want to send a token in JQ DataTable ajax request header.
Just like a regular ajax call like this
$.ajax({
url: url,
type: 'POST',
data: data, // data I want to post at server
contentType: 'application/json; charset=utf-8',
headers: {
'Token': Token //token I want to send in ajax header
},
cache: false,
async: async,
beforeSend: function () {
},
complete: function () {
},
success: function (user, status, XHR) {
},
error: function (req, status, error) {
}
});
you can add it in beforeSend, so your ajax would look something like this:
"ajax": {
"url" : 'changeToYourUrl',
"type" : 'POST/GET',
"beforeSend" : function(xhr) {
xhr.setRequestHeader('TOKEN',token);
}
hope this helps.
I found this usefull. JqDataTable how to add authorization header to ajax requests.
can anyone please tell me why this is bad request
var searchurl = "https://accounts.google.com/o/oauth2/token";
$.ajax({
dataType: "json",
url:searchurl,
context: {code:auth_code, client_id:'clientid', client_secret:'secret', redirect_uri:'http%3A%2F%2Flocalhost:8085%2FGmailIntegration%2FgetAuthResponse.jsp', grant_type:'authorization_code'},
type:"POST",
contentType:"application/x-www-form-urlencoded",
success:function(data) {
alert(data);
},
error: function(jqXHR, exception) {
console.log(jqXHR);
}
});
I got this working.. i am sharing the code for those who are stuck with this:
$.ajax({
dataType: "json",
url:searchurl,
data: {code:code, client_id:'clientid', client_secret:'secret', redirect_uri:'http://localhost:8085/GmailIntegration/getAuthResponse.jsp', grant_type:'authorization_code'},
type:"POST",
contentType:"application/x-www-form-urlencoded; charset=utf-8",
crossDomain:true,
cache : true,
success:function(data) {
alert(data);
},
error: function(jqXHR, exception, errorstr) {
console.log(jqXHR);
alert(errorstr);
}
});
but now i have new issue. The url get 200 OK response but i am not getting response at all
OAuth2 user agent flow is recommended for JS clients, see https://developers.google.com/accounts/docs/OAuth2UserAgent
Is there any specific reason you want to use the web server flow in a JS app?