I've looked at many similar questions on here, but I am unable to get to the bottom of this issue.
I've built a Web API, and if I post at it using curl as follows:
curl -i -H "Content-Type: application/json" -X POST -d '{"password":"abcd"}' http://<ip>:5000/api/v1.0/state
My API receives the message and records:
<Request 'http://<ip>:5000/api/v1.0/state' [POST]>
{u'password': u'abcd'}
192.168.1.100 - - [08/Feb/2016 21:04:32] "POST /api/v1.0/stateHTTP/1.1" 200 -
So far so good....
I've built a webpage with the following code (I am brand new to web dev), which I am using to post against this API:
function myFunction() {
$.ajax({
url: "http://" + document.domain + ":5000/api/v1.0/state",
method: "POST",
dataType:"json",
data: {"password" : "John"},
success: function(data){
alert(data);
}
});
}
When calling this function, the post is clearly recieved by my API, but without any data:
<Request 'http://<ip>:5000/api/v1.0/state' [POST]>
None
192.168.1.120 - - [08/Feb/2016 21:09:53] "POST /api/v1.0/state HTTP/1.1" 200 -
I've tried using a $.post method:
$.post(
"http://" + document.domain + ":5000/api/v1.0/state",
JSON.stringify({"password" : "password" }) ,
function(data) {
alert("Response: " + data);
}
);
And I get the same result.
EDIT: Tried using the following code, as suggested by an answer below:
$.ajax({
url: "http://" + document.domain + ":5000/api/v1.0/state",
method: "POST",
dataType:"json",
contentType:'application/json',
data: JSON.stringify({"password" : "John"}),
success: function(data){
alert(data);
}
});
And I receive an OPTIONS API response:
192.168.1.120 - - [08/Feb/2016 21:31:28] "OPTIONS /api/v1.0/state HTTP/1.1" 200 -
Any thoughts? I'm able to hit the server, but can't get any JSON data across.
Thanks!
By your curl snippet it looks like your endpoint is expecting a JSON request payload. jQuery does not set a content-type request header of application/json, so you have to actually tell it to do so:
$.ajax({
url: "http://" + document.domain + ":5000/api/v1.0/state",
method: "POST",
dataType:"json",
contentType:'application/json',
data: JSON.stringify({"password" : "John"}),
success: function(data){
alert(data);
}
});
Also note if this is being used on a different domain, meaning not "http://" + document.domain + ":5000, you may end up hitting a CORS issue.
Related
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.
I'm trying to call a PUT request on JsonBlob but i get this error
"XML interpretation error: no root element found Address: https://jsonblob.com/api/jsonBlob/43c83fba-f591-11e8-85a9-1542923be246 Row number 1, column 1:"
Here is the function:
backup : function(data){
data = JSON.stringify(data);
console.log(data);
var url = "https://jsonblob.com/api/jsonBlob/43c83fba-f591-11e8-85a9-1542923be246";
$.ajax({
url: url,
type: "PUT",
data: data,
dataType: 'json',
error:function(xhr, status, e){
console.log(status)
}
});
The API's error message indicates that it is trying to parse your request as XML.
The documentation for the API shows a Content-Type header on the request:
HTTP/1.1 200 OK
Content-Type: application/json
Transfer-Encoding: chunked
{"people":["fred","mark","andrew"]}
You haven't included that.
Add it:
$.ajax({
url: url,
contentType: "application/json"
I should make a json call with javascript:
var arr = { username: "user#user.com", password : "mypassword" , portfolioID : "xxxxxxxxxxxxxxxxx" };
$.ajax({
url: 'https://siam.eseye.com/login',
type: 'POST',
data: JSON.stringify(arr),
dataType: "json",
contentType: 'application/json; charset=utf-8',
async: false,
success: function(msg) {
alert(msg);
}
});
the error that comes back to me : CORS header " Access- Control-Allow -Origin " missing .
Attention, before saying that it is a double question , read here , I searched online and I did :
inserted header ( " Access- Control-Allow -Origin : * " ) ;
Wamp > Apache > Apache Modules > headers_module enabled
added the datatype
dataType: json or jsonp the error remain
after all of this evidence , it will not work the same .
Is there anything else I forgot to try?
with Postman the API work.
Thank you.
You may need to use dataType: "jsonp" which is use for cross site scripting.Check here for more about jsonp
I created this JSFIDDLE. The request semms to be served but the response have error. You can validate it console in developer's tool
I have some JavaScript (physical file located in /SiteAssets library) that should delete an item in a SharePoint list.
We have existing JavaScript code that retrieves data from the list - it looks like this:
(notice that since the JavaScript runs on a PDP in context of the current user, we don't need a specific access token for the request)
var data = $.ajax({
url: projSiteUrl + "/_api/lists/getbytitle('<listname>')/items,
type: "GET",
dataType: "json",
async: false,
headers: {
Accept: "application/json;odata=verbose"
}
});
So I thought that I could write similar code to delete an item from the list again. I read on https://msdn.microsoft.com/en-us/library/office/jj164022.aspx#HTTPOps that the REST endpoint of SharePoint supports the "normal" REST verbs, so I wrote this, using the DELETE HTTP verb.
var restUrl = spSiteUrl + '/_api/web/lists/GetByTitle(\'' + listTitle + '\')/items(' + itemId + ')';
jQuery.ajax({
url: restUrl,
type: "DELETE",
headers: {
Accept: "application/json;odata=verbose"
}
})
But I am getting a 403 (FORBIDDEN) when requesting.
I guess the question is: Am I wrong in assuming that the DELETE verb is supported?
Thanks :-)
Ok, so apparently I do need the digest when doing modifications - but not for simple data retrieval.
If I change my code to
jQuery.ajax({
url: restUrl,
type: "DELETE",
headers: {
Accept: "application/json;odata=verbose",
"X-RequestDigest": $("#__REQUESTDIGEST").val(),
"IF-MATCH": "*"
}
}).
... it works with a simple AJAX request using the REST HTTP verb DELETE :-)
to get SharePoint List dataI am having an issue accessing the REST server via the CSOM. I have tried this with both the CSOM and just using jQuery. Code examples and the associated errors below. Can anyone direct me to a working example or tell me what I am doing wrong?
This code is part of a SharePoint Hosted App and the list is just a list in the root web. The user has permission to access the list and the app.
CSOM Example:
Yields:
Fail! : App Web is not deployed for this app's request url http://mySharePointRootWebURL.local.
var data = new SP.RequestExecutor("http://mySharePointRootWebURL.local/");
data.executeAsync({
method: "GET",
headers: { "Accept": "application/json;odata=verbose" },
url: "http://mySharePointRootWebURL.local/_api/web/lists/getbytitle(\'MyLstName\')/items",
success: function (data) { console.log('success!'); },
error: function (p1,p2,errorMessage) { console.log('Fail! :' + errorMessage); }
});
I can see that this example is not hitting the root web at all (from the app / app web).
jQuery Example
Yields:
Resource interpreted as Script but transferred with MIME type text/plain: "http://mySharePointRootWebURL.local/_api/web/lists/getbytitle(\'MyLstName\')/items&…Query19104068602353800088_1379462071044&alt=json-in-script&_=1379462071045". jquery.js:9597
Uncaught SyntaxError: Unexpected token < items:1
fail! : Error: jQuery19104068602353800088_1379462071044 was not called
$.ajax({
url: "http://mySharePointRootWebURL.local/_api/web/lists/getbytitle(\'MyListName\')/items",
type: "GET",
beforeSend: function(xhr){
xhr.setRequestHeader('Accept', 'application/json;odata=verbose'); },
headers: {"Accept":"application/json;odata=verbose"},
success: function(data){ console.log("success"); },
error: function errHandler(p1,p2,errMessage){ console.log("fail! : " + errMessage); },
dataType: 'jsonp',
crossDomain: true,
data: {
alt: 'json-in-script'
},
});
This is working as far as accessing the REST server and returning data, the problem is that the headers are not being added at all (verified in Fiddler). Without the headers the data comes back in XML. If that's how it has to be I will work with it, I guess, but I'd prefer to get JSON.
Your code doesn't look right. Here's code that wors with the cross-domain library
var executor = new SP.RequestExecutor(appweburl);
executor.executeAsync(
{
url:
appweburl +
"/_api/SP.AppContextSite(#target)/web/lists/getByTitle('Contacts')/items" +
"?#target='" + hostweburl + "'" +
"&$select=Id,FirstName,Title,WorkPhone,Email" +
"&$orderby=Title,FirstName",
method: "GET",
headers: { "accept": "application/json;odata=verbose" },
success: successHandler,
error: errorHandler
})