jquery - AJAX POST with CORS to API Gateway does not work, although can POST with CURL -
so trying submit data api endpoint using $.ajax() call. have verified can post using curl
command, in format of following:
curl -x post -h "content-type: application/json" -d "{\"uname\":\"myusername2\",\"emailaddr\":\"user2@ex.com\"}" <url api endpoint>
that curl
command returns empty json response (looks {}
), , data gets put db (which configured api gateway endpoint do).
however, when try using $.ajax()
command, programmed fire on button being clicked after form data filled out, can't work.
var obj = new object(); obj.uname = $uname; obj.emailaddr = $email; var stringedobj = json.stringify(obj); alert("stringified: " + stringedobj); $.ajax({ url: '<same url in curl>', type: 'post', contenttype: 'application/json', datatype: 'json', data: json.stringify(obj), success: function(data) { alert(json.stringify(data)); }, error: function(e) { alert("failed" + json.stringify(e)); } });
whenever run this, can see first alert message data stringified. however, error message looks this:
failed{"readystate":0,"responsetext":"","status":0,"statustext":"error"}
i know if can more detailed error response. also, have tried parsedata: false
, crossdomain: true
. once again, works when use curl pretty sure not api gateway configuration issue.
thanks , help!
edit: learned comment below javascript console. have found out due cors not being enabled. enabled cors in aws api gateway, waited complete, changed request to:
$.ajax({ url: '<my url>', type: 'post', data: json.stringify(obj), datatype: 'json', crossdomain: true, success: function(data) { alert(json.stringify(data)); }, error: function(e) { alert("failed" + json.stringify(e)); } });
and same response in javascript console needing cors. other threads on cors have shown example. wondering if need custom headers, although tried adding headers: { "access-control-allow-origin": "*" }
, still got same response javascript console:
cross-origin request blocked: same origin policy disallows reading remote resource @ https://k6i6wk8487.execute-api.us-west-2.amazonaws.com/prod/comments. (reason: cors header 'access-control-allow-origin' missing).
figured out, had not hit 'deploy' in aws api gateway after updating enable cors. doh! helped. here final ajax call:
$.ajax({ url: $invokeurl, type: 'post', data: json.stringify(obj), datatype: 'json', crossdomain: true, contenttype: 'application/json', success: function(data) { alert(json.stringify(data)); }, error: function(e) { alert("failed" + json.stringify(e));
thanks helped, , let me know if running issue api gateway , try help.
Comments
Post a Comment