I am a problem with simple javascript web page hosted on AWS S3 that makes a HTTP POST to AWS API Gateway using ajax.
I am able to make a call using curl with success:
curl -X POST -H "Content-Type: application/json" https://xxxx.execute-api.eu-west-1.amazonaws.com/dev/ankieta --data #data.json
data.json file:
{ "imie": "jasiu",
"ocena": "6",
"opinia": "niezle"
}
My javascript code looks like this.
<html>
<body>
<title>Ankieta</title>
<h1>Wypelnik ankiete</h1>
<button type="button" onclick="uruchom()">JSON</button>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript">
function uruchom() {
var resultDiv = $("#resultDivContainer");
var myData = {"imie": "Michal"};
$.ajax({
url: "https://xxxx.execute-api.eu-west-1.amazonaws.com/dev/ankieta",
type: "POST",
data: JSON.stringify(myData),
crossDomain: true,
contentType: "application/json",
dataType: 'jsonp',
headers: {
"Access-Control-Allow-Origin": "*"
},
success: function () {
alert("ok");
},
error: function() {
alert("zonk");
}
});
};
</script>
</body>
</html>
This is the error I get from web debug:
GET https://xxxx.execute-api.eu-west-1.amazonaws.com/dev/ankieta?callback=jQuery17203000220305941388_1546897907447&{%22imie%22:%22Michal%22}&_=1546897908872 net::ERR_ABORTED 400
It looks like there is problem with callback and in the URL is altered with my data from body. In my case I don't want to check whenever the callback is fine - want to simply POST data.
Thanks for any suggestions.
POST can't be used to send a JSONP request. JSONP doesn't actually use AJAX, it works by creating a <script> tag whose src is the URL. There's no way to send POST data this way, so the data is added as URL parameters.
If this API expects the JSON in POST data, you can't use dataType: 'jsonp'. You have to use dataType: 'json'. If the API doesn't allow CORS, you'll need to use a proxy on your server to make the actual request, you can't do it directly from the browser.
Dont stringify the data object. JQuery does this for you. Just pass object.
var myData = {"imie": "Michal"};
$.ajax({
url: "https://xxxx.execute-api.eu-west-1.amazonaws.com/dev/ankieta",
type: "POST",
data: myData,
crossDomain: true,
contentType: "application/json",
dataType: 'jsonp',
headers: {
"Access-Control-Allow-Origin": "*"
},
success: function () {
alert("ok");
},
error: function() {
alert("zonk");
}
});
Thanks for suggestions and answers especially in CORS direction. I was sure my API GW has CORS enabled, but didn't check AWS Lambda that is behind it and found that I was not returning "Access-Control-Allow-Origin" header back to client.
exports.handler = function(event, context, callback) {
callback(null, {
"statusCode": 200,
"headers": {
"Access-Control-Allow-Origin": "*"
}
});
};
After applying this, I can send HTTP POST.
Related
My question is very simple and I thought creating this program would only take a couple hours. However now I have been working on it all day trying to figure out what I could be doing wrong.
All I am trying to do is post messages to slack using their postMessage api. I have been able to send messages succesfully using slacks testing methods.
This is the url that is outputted by the test
https://slack.com/api/chat.postMessage?token=xoxp-xxxxxx-xxxxxxxx-xxxxxxxx-xxxxxxxxxxx&channel=XXXXXXXX&text=Just%20need%20the%20url&as_user=jheuman&pretty=1
I then decided to try it out locally using this html file served from my file system
<!DOCTYPE html>
<html>
<head>
<title>Testing Slack API</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
<button onClick="test()">Test</button>
<button onClick="test2()">Authorization Test</button>
<script>
function test() {
var apiUrl = "https://slack.com/api/chat.postMessage";
var token = "xoxp-xxxxx...";//my token has been omitted for security;
var channel = "#general";
var text = "Testing slack api";
var user = "jheuman";
var actualToken = "Bearer " + token;
$.ajax({
headers: {
'Authorization':actualToken,
'Content-Type':'application/json'
},
data: JSON.stringify({
"channel": channel,
"text": text,
"as_user": user
}),
dataType: 'json',
processData: false,
type: 'POST',
url: apiUrl
})
.done(function(data) {
console.log(JSON.stringify(data));
})
.fail(function(response) {
console.log(JSON.stringify(response));
});
};
function test2() {
var apiUrl = "https://slack.com/api/auth.test";
var token = "xoxp-xxxxx..."; //my token has been omitted for security
var channel = "#general";
var text = "Testing slack api";
var user = "jheuman";
var actualToken = "Bearer" + token;
$.ajax({
headers: {
'Authorization':actualToken
},
type: 'POST',
url: apiUrl,
})
.done(function(data) {
console.log(JSON.stringify(data));
})
.fail(function(response) {
console.log(JSON.stringify(response));
});
};
</script>
But when I click either button I get the following error:
Failed to load https://slack.com/api/chat.postMessage: Request header field
Authorization is not allowed by Access-Control-Allow-Headers in preflight
response.
So per a friends Suggestion I tried it out on a server. I used Web Server For Chrome to serve it up on port 8887. First without setting cors headers and then with setting cors headers. Both to no avail. I received the same error.
As you can see I also tried the auth.test call but I receive the same error.
Slack specifically states that they prefer an authorization header and that the api can handle json data.
Other things I have tried:
Having no header field with token in data:
data: JSON.stringify({
'token':actualToken,
'channel': channel,
'text': text,
'as_user': user
}),
dataType: 'json',
processData: false,
type: 'POST',
url: apiUrl
Errors received:
{"ok":false,"error":"invalid_form_data"}
Having no header field with token in data without 'Bearer':
data: JSON.stringify({
'token':token,
'channel': channel,
'text': text,
'as_user': user
}),
dataType: 'json',
processData: false,
type: 'POST',
url: apiUrl
Errors received:
{"ok":false,"error":"invalid_form_data"}
Things I have looked into but don't think will effect outcome
The type of token
So how do I get this post request to work?
I am not set on jquery or ajax, it is just what I have used in the past so if you have a different request library to use I'm all ears.
If you need more information I will try to give it to you
Since configuring CORS correctly for sending data with content-type application/json can be tricky, I would suggest to send the request as application/x-www-form-urlencoded which is the default for AJAX.
Example:
var apiUrl = "https://slack.com/api/chat.postMessage";
var token = MY_TOKEN;
var channel = "general";
var text = "Testing slack api";
var user = "jheuman";
$.ajax({
data: {
"token": token,
"channel": channel,
"text": text,
"as_user": user
},
dataType: 'text',
type: 'POST',
url: apiUrl,
error: function(xhr,status,error){
console.log("error: " + error);
},
success: function(data) {
console.log("result: " + data);
}
});
In case you get CORS errors, you can add crossDomain: true
This solution is tested and works when run in a normal browser.
You need to reply to that CORS preflight with the appropriate CORS headers to make this work. One of which is indeed Access-Control-Allow-Headers. That header needs to contain the same values the Access-Control-Request-Headers header contained (or more).
https://fetch.spec.whatwg.org/#http-cors-protocol explains this setup in more detail.
headers: {
'Authorization':actualToken,
'Content-Type':'application/json',
'Access-Control-Allow-Headers':'x-requested-with'
},
I am trying to make a POST call using AJAX. Here's my controller:
#RequestMapping(method = RequestMethod.POST, value = "/submitsignup")
#ResponseBody
public String persistSignupData(#RequestBody SignupModel signupModel) {
signupDaoImpl.persistSignupData(signupModel);
return "success";
}
Javascript:
$(document).ready(function() {
$("#password2").keyup(checkPasswordMatch);
$('#signup-button').click(function() {
$.ajax({
type: "POST",
url: "/cinestop/submitsignup",
data: JSON.stringify(getFormDataJSON()),
contentType: "application/json",
dataType: "json"
});
});
});
When I make the call, a 404 is returned. I have been unable to debug this problem till now. What is it that I am doing wrong?
When I make the call, a 404 is returned.
Did you ensure that you put the correct url in your ajax part..?
HTTP error 404 usually means that the document that you'r requesting can't be loaded because it's
not existing
it is not readable
the mime type for the document is not defined (usually a problem of common webservers, i dont think that this matches on your specific setup)
Quote of relevant code
url: "/cinestop/submitsignup",
#RequestMapping(method = RequestMethod.POST, value = "/submitsignup")
Avoid stringifying the JSON, since your datatType expected is JSON.
$(document).ready(function() {
$("#password2").keyup(checkPasswordMatch);
$('#signup-button').click(function() {
$.ajax({
type: "POST",
url: "/cinestop/submitsignup",
data: getFormDataJSON(),
contentType: "application/json",
dataType: "json"
});
});
});
First try to debug the application step by step
From postman, curl or any other rest client try to hit a post call with the payload body as empty JSON.If this also return 404, then it is a server problem.If it succeeds or throw any java error then we know it is UI error.Also make sure to add content type header as 'application/json'
This will help in isolating the issue and will help us in giving a quick resolution
Try to run this solution:
var settings = {
"url": "/cinestop/submitsignup",
"method": "POST",
"headers": {
"Content-Type": "application/json"
},
"data": getFormDataJSON()
}
$.ajax(settings).done(function (response) {
console.log(response);
});
This question already has answers here:
CORS error when jquery ajax request on api
(2 answers)
Closed 5 years ago.
I have here a strange situation with AJAX call, how to pass api key in header:
My full url for my json is: https://apifootball.com/api/?action=get_events&from=2017-10-30&to=2017-11-01&APIkey=fd6b8ec7d651960788351ee2b1baffba6ac1a9c8eb047118a1a823c247bdade0
And I am trying now to pass API key in headers of ajax call, but still have this error from console:
"Failed to load https://apifootball.com/api/?action=get_events&from=2017-10-30&to=2017-11-01&: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://bigsportlive.com' is therefore not allowed access."
Here is my ajax call:
var apiKey = "fd6b8ec7d651960788351ee2b1baffba6ac1a9c8eb047118a1a823c247bdade0";
$.ajax({
type: "GET",
url: "https://apifootball.com/api/?action=get_events&from=2017-10-30&to=2017-11-01",
headers: { "APIkey": apiKey },
success: function(result){
result[i].league_name
}
});
May be I am doing something not correct?
Thanks!
If you want to add a header (or a set of headers) to each request, use the beforeSend hook with $.ajaxSetup ():
$.ajaxSetup({
beforeSend: function(xhr) {
xhr.setRequestHeader('x-my-custom-header', 'some value');
}
});
// Sends your custom header
$.ajax({ url: 'your/url' });
// Sends both custom headers
$.ajax({ url: 'your/url', headers: { 'x-some-other-header': 'some value' } });
Another solution consist to use lowercase for headers
$(document).ready(function () {
$.ajax({
url: "http://xx.xx.xx.xx:xx/api/values",
type: "GET",
dataType: "json",
headers: { "HeaderName": "MYKey" }
});
});
Yes, there is an Access-Control-Allow-Origin error.
If so, you may want a php backend to get this for you, I believe, using
<?php
$data = file_get_contents("https://apifootball.com/api/?action=get_events&from=2017-10-30&to=2017-11-01&APIkey=fd6b8ec7d651960788351ee2b1baffba6ac1a9c8eb047118a1a823c247bdade0");
echo json_encode($data);
?>
Then use an ajax call to this file.
$.ajax({
type: "GET",
url: 'name_of_php_file.php',
dataType: "json",
success: function(result){
alert(result);
}
});
I'm trying to write a plugin for TFS 2015 (its important). I read a couple of manuals. the examples all turns out simply, but it is more difficult with a real plugin. my problem: i cant send any get/post request from my tfs server to same server. I always get the same response: 401 Unauthorized. I looked at examples that sending Ajax requests (https://github.com/ALM-Rangers/Work-Item-Details-Widget-Extension/blob/master/src/scripts/menu.js) and add auth token to request, but i get same error 401.
my code:
VSS.require(["VSS/Authentication/Services"], function(Services) {
var authTokenManager = Services.authTokenManager;
VSS.getAccessToken().then(function(token) {
var header = authTokenManager.getAuthorizationHeader(token);
$.ajaxSetup({
headers: { 'Authorization': header }
});
$.ajax({
url: "http://myTFSServ:8080/tfs/_api/_common/GetCollectionJumpList?__v=5&navigationContextPackage=%7B%22Action%22%3A%22index%22%2C%22Area%22%3A%22%22%2C%22Level%22%3A8%2C%22Controller%22%3A%22workItems%22%7D&selectedHostId=6e60eeec-39b3-4902-a864-172cd27dea91&api-version=3.0-preview.2",
type: "GET",
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function(c) {
debugger;
// do something...;
},
error: function(e) {
debugger;
var error = e;
}
});
});
});
how can i send any valid get/post request from my tfs server to same server??
I'm trying to convert the curl code from an API called TextRazor to jquery's AJAX because of a platform limitations. I have tried many solutions from similar questions by the community but can't seem to get any data back (through the alert dialog). If it matters
from the documentation calling the API looks like this:
curl -X POST \
-H "x-textrazor-key: YOUR_API_KEY" \
-d "extractors=entities,entailments" \
-d "text=Spain's stricken Bankia expects to sell off..." \
https://api.textrazor.com/
My current AJAX code looks like this:
$.ajax({
url: "https://api.textrazor.com/",
type: "POST",
dataType: 'json',
data: {
x-textrazor-key: "YOUR_API_KEY",
extractors: "entities,entailments",
text:"Spain's stricken Bankia expects to sell..."
},
success:function(data) {
alert(JSON.stringify(data));
},error: function(xhr) {
alert("<some error>");
console.error(xhr.responseText);
}});
here is the link to jsfiddle if it helps: jsfiddle.net
Thanks for your support!
I think you have to pass "x-textrazor-key: YOUR_API_KEY" as additional header
$.ajax({
url: "https://api.textrazor.com/",
type: "POST",
dataType: 'json',
beforeSend: function(xhr){xhr.setRequestHeader('x-textrazor-key', 'YOUR_API_KEY');},
data: {
extractors: "entities,entailments",
text:"Spain's stricken Bankia expects to sell..."
},
success:function(data) {
alert(JSON.stringify(data));
},error: function(xhr) {
alert("<some error>");
console.error(xhr.responseText);
}});
data: {
x-textrazor-key: "YOUR_API_KEY",
The data: bracket in jQuery means that you want to send that data as POST, while you need to send the API key as a header.
Add this field to your code (after URL or so):
headers: {"x-textrazor-key": "YOUR_API_KEY"}
This looks close to me, but you put the header into the POST body. I think it should be the below. (Note that you also need quotes around 'x-textrazor-key', since the dashes in it will otherwise be interpreted as subtraction.)
$.ajax({
url: "https://api.textrazor.com/",
type: "POST",
dataType: 'json',
headers: {
'x-textrazor-key': "YOUR_API_KEY"
},
data: {
extractors: "entities,entailments",
text: "Spain's stricken Bankia expects to sell..."
},
success: function (data) {
alert(JSON.stringify(data));
},
error: function (xhr) {
alert("<some error>");
console.error(xhr.responseText);
}
});
There could of course be other issues here. (E.g. perhaps the API doesn't support cross-origin requests.) You'll want to take a look at the network tab in your browser's developer tools to see what actually happens.