Issue
I need to post json data to AWS API gateway which is protected by an API key. When I tried adding x-api-key header in Postman and made the request, the POST worked. However, I want to do the same thing with Jquery code. How do I add this x-api-key header in JQuery. Here is my code,
var myJSON = JSON.stringify(obj);
$.ajax({
type: "POST",
url: "<aws-url>" ,
data: myJSON,
crossDomain : true,
dataType: 'json',
beforeSend: function(xhr){xhr.setRequestHeader("X-Api-Key","<value>");},
headers :{
'Content-Type':'application/x-www-form-urlencoded',
//'Authorization':'<value>'
},
success: function(result) {
console.log("ho gaya");
}
});
As you can see, I have tried adding "Authorization", "auth-key","AUTH-KEY", "X-Api-Key", "x-api-key" in the header section. I also added the header in the beforeSend section which again didn't work. Please help.
Solution
Took too long for me to figure this out, and maybe this is a solution to a different issue but this question is the most similar to mine - have a lambda function accessed by API gateway, protected by x-api-key, and I can submit POST request via .NET but fail in jquery/ajax.
1) Use the same ajax script posted, remove the beforeSend and Content-Type keyname and value in the header construction.
2) Enable CORS following the aws procedure. Make sure you apply this to your POST/GET function and not the RESOURCE:
https://docs.aws.amazon.com/apigateway/latest/developerguide/how-to-cors.html
3) In step 5, Allow-Access-Control-Headers should have X-Api-Key, simply change it to lowercase.
From these steps it seems essential that CORS is enabled, and the lowercase of the x-api-key isn't as vital as long as you make your request header keyname consistent. Lastly, this whole process should occur after you've already created your usage plan and API key in the API Gateway console.
$.ajax({
type: "POST",
url: <url>,
data: <myJSON>,
crossDomain: true,
dataType: 'json',
headers: {"x-api-key": <keyvalue>},
success: function(response) {
$('#output').html('Success');
},
error: function(response) {
$('#output').html('Failure');
},
});
Answered By - Phil P Answer Checked By - Dawn Plyler (PHPFixing Volunteer)
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.