I'm using core-ajax to retrieve JSON data just fine. Turning the component around to post back to the server as JSON is another thing altogether. In all cases, and irrespective of the contentType or handleAs parameters passed in, it appears that my JSON object I'm passing in as an input is being converted back to key=value in the server headers.
The code:
var ajax = document.querySelector('core-ajax');
ajax.method = 'POST';
ajax.handleAs = 'JSON';
ajax.contentType = 'application/json';
ajax.params = JSON.stringify(data);
ajax.go();
Really straightforward. The logs in Go give me:
2014/07/22 14:23:09 utils.go:139: OPTIONS /1/users/173?access_token=(token)
2014/07/22 14:23:09 utils.go:124: POST /1/users/173?access_token=(token)
2014/07/22 14:23:09 users.go:379: full_name=Greg%20Johnson
We've verified that there's no transformation happening on our side. Request headers are going out just fine.
I could completely be missing something. How else can we successfully POST out JSON data?
.params is for URL params. What you want is to post the JSON as the request body? For that, I believe you need to set the .body property:
This should do the trick:
ajax.body = data
See https://github.com/Polymer/core-ajax/blob/master/core-ajax.html#L151
Related
I'm trying to extract a SessionId from the XML which is returned from a SOAP API.
I've read through the Postman documentation (several times over) but it wasn't the most helpful in achieving my goal.
What was suggested in a few blogs was to convert the XML to JSON, and then pick out the token and it's value from there, but that didn't help either.
I used the following in my Test:
var jsonObject = xml2Json(responseBody);
postman.setGlobalVariable("Session_Id", jsonObject.SessionID);
The above created the variable "Session_Id" but didn't actually assign a value to it. I'm stumped.
I'm definitely retrieving the data from the API, and it's viewable in Postman's "Body" Response.
To extract a variable from XML using Postman, first convert your XML to JSON, using the xml2Json converter method:
var responseJson = xml2Json(responseBody);
(Where "responseBody" is your xml body.)
Then use the console.log method to output your JSON data, as such:
console.log(responseJson);
Be sure to have followed this tutorial on Enabling Chrome Dev Tools in Postman
Inside your Test Runner, run the test, then right click and "Inspect" anywhere in the Runner. Select the "Console" tab once Chrome's Dev Tools launch. Expand the "Object" part.
Then drill-down (expand) until you see the Property whose data you need.
Thereafter, set the variable by appending each drill-down level to the parameter you want:
postman.setGlobalVariable("Session_Id", responseJson.UserSessionToken.SessionID);
In this case, "responseJson" is the object, "UserSessionToken" was the next level in the drill-down, and SessionId was the parameter I needed within that.
Note: This answer was the correct solution before v7.15.0 of postman. For versions later than this, the accepted answer may not work.
Since Postman v7.15.0 the accepted answer did not work for me (it used to before the update). You have to put the path segments into square brackets.
For example, in the following XML response:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<QuotesPrivateResponse>
<lease-service>
<duration-in-months>24</duration-in-months>
</lease-service>
</QuotesPrivateResponse>
to retrieve the value duration-in-months:
var response = xml2Json(responseBody);
var duration = response["QuotesPrivateResponse"]["lease-service"]["duration-in-months"];
pm.environment.set("duration", duration);
My strong suspicion is that this behaviour is caused when any of the element names contain hyphens.
Postman v7.20.1
I'd like to add my answer since above there are a couple of details that took me a while to solve:
how to cope with a multipart SOAP response
how to manage a JSON object
responseBody definition
Here's the first lines of my XML response to analyze:
------=_Part_694527_1470506002.1584708814081
Content-Type: application/xop+xml;charset=UTF-8;type="text/xml"
Content-Transfer-Encoding: 8bit
Content-ID:
<e3bd82ac-d88f-49d4-8088-e07ff1c8d407>
<?xml version="1.0" encoding="UTF-8" ?>
<env:Envelope xmlns:env="http://schemas.xmlsoap.org/soap/envelope/">
<env:Header/>
<env:Body>
<ns2:GenericResponse xmlns:ns2="http://XXXXXXXX">
<ns2:Service IdcService="XXXXXXXX">
<ns2:Document>
<ns2:Field name="XXXXXXXX:isSetDefault">1</ns2:Field>
<ns2:Field name="XXXXXXXX">CHECKIN_UNIVERSAL</ns2:Field>
After I noticed it was a multipart I've ended up with this Postman Test:
var response = pm.response.text();
var responseBody = response.substr(response.indexOf('<env:'));
pm.test("The body of the response is a valid XML", function () {
pm.expect(xml2Json(responseBody)).to.exist;
});
pm.test("UCM file upload checkin succesfull", function(){
var responseJson = xml2Json(responseBody);
var JsonFields = (responseJson['env:Envelope']['env:Body']['ns2:GenericResponse']['ns2:Service']['ns2:Document']['ns2:Field']);
JsonFields.forEach( field => {
if (field.name == 'StatusMessage'){
console.log("Field = " + field.name);
pm.expect(field.text().to.include("Successfully checked in"));
}
});
});
Blizzard just shut down their old API, and made a change so you need an apikey. I changed the URL to the new api, and added the API key. I know that the URL is valid.
var toonJSON = UrlFetchApp.fetch("eu.api.battle.net/wow/character/"+toonRealm+"/"+toonName+"?fields=items,statistics,progression,talents,audit&apikey="+apiKey, {muteHttpExceptions: true})
var toon = JSON.parse(toonJSON.getContentText())
JSON.pase returns just an empty object
return toon.toSorce() // retuned ({})
I used alot of time to see if i could find the problem. have come up empty. Think it has something to do with the "responce headers".
Responce headers: http://pastebin.com/t30giRK1 (i got them from dev.battle.net (blizzards api site)
JSON: http://pastebin.com/CPam4syG
I think it is the code you're using.
I was able to Parse it by opening the raw url of your pastebin JSON http://pastebin.com/raw/CPam4syG
And using the following code
var text = document.getElementsByTagName('pre')[0].innerHTML;
var parse = JSON.parse(text);
So to conclude I think it is the UrlFetchApp.fetch that's returning {}
So i found the problems:
I needed https:// in the URL since i found after some hours that i had an SSL error
If you just use toString instead of getContentText it works. Thow why getContentText do not work, i am not sure of.
was same problem, this works for me (dont forget to paste your key)
var toonJSON = UrlFetchApp.fetch("https://eu.api.battle.net/wow/character/"+toonRealm+"/"+toonName+"?fields=items%2Cstatistics%2Cprogression%2Caudit&locale=en_GB&apikey= ... ")
I'm using Ember-Data 1.0.0.Beta-9 and Ember 1.7 to consume a REST API via DreamFactory's REST Platform. (http://www.dreamfactory.com).
I've had to extend the RESTAdapter in order to use DF and I've been able to implement GET and POST requests with no problems. I am now trying to implement model.save() (PUT) requests and am having a serious hiccup.
Calling model.save() sends the PUT request with the correct data to my API endpoint and I get a 200 OK response with a JSON response of { "id": "1" } which is what is supposed to happen. However when I try to access the updated record all of the properties are empty except for ID and the record on the server is not updated. I can take the same JSON string passed in the request, paste it into the DreamFactory Swagger API Docs and it works no problem - response is good and the record is updated on the DB.
I've created a JSBin to show all of the code at http://emberjs.jsbin.com/nagoga/1/edit
Unfortunately I can't have a live example as the servers in question are locked down to only accept requests from our company's public IP range.
DreamFactory provides a live demo of the API in question at
https://dsp-sandman1.cloud.dreamfactory.com/swagger/#!/db/replaceRecordsByIds
OK in the end I discovered that you can customize the DreamFactory response by adding a ?fields=* param to the end of the PUT request. I monkey-patched that into my updateRecord method using the following:
updateRecord: function(store, type, record) {
var data = {};
var serializer = store.serializerFor(type.typeKey);
serializer.serializeIntoHash(data, type, record);
var adapter = this;
return new Ember.RSVP.Promise(function(resolve, reject) {
// hack to make DSP send back the full object
adapter.ajax(adapter.buildURL(type.typeKey) + '?fields=*', "PUT", { data: data }).then(function(json){
// if the request is a success we'll return the same data we passed in
resolve(json);
}, function(reason){
reject(reason.responseJSON);
});
});
}
And poof we haz updates!
DreamFactory has support for tacking several params onto the end of the requests to fully customize the response - at some point I will look to implement this correctly but for the time being I can move forward with my project. Yay!
EmberData is interpreting the response from the server as an empty object with an id of "1" an no other properties in it. You need to return the entire new object back from the server with the changes reflected.
I have created a WebAPI project to help capture statements from a TinCan learning course but I am having extreme difficulty in retrieving any of the Request payload details. Within this payload I pass the whole statement that I am trying to capture but upon trying to read using:
var test = Request.Content.ReadAsFormDataAsync().Result.ToString();
I get the following error message:
No MediaTypeFormatter is available to read an object of type 'FormDataCollection' from content with media type 'application/json'.
I have tried Converting the result object to JSON to overcome this problem but it has not been any use. Do I need to configure json somewhere in the configuration? I have tried adding
var appXmlType = config.Formatters.XmlFormatter.SupportedMediaTypes.FirstOrDefault(t => t.MediaType == "application/xml");
config.Formatters.XmlFormatter.SupportedMediaTypes.Remove(appXmlType);
and also:
var jsonFormatter = config.Formatters.JsonFormatter;
config.Formatters.Insert(0, jsonFormatter);
to my WebApiConfig.cs file as answered in another question of how to return json but I cannot seem to pass this error. I have also set config.formatter to accept application/json but this also has not worked
CONTROLLER CODE
public void Put([FromBody]string statementId)
{
var test = Request.Content.ReadAsFormDataAsync().Result;
System.Diagnostics.EventLog.WriteEntry("Application", "/xAPI/PUT has been called", System.Diagnostics.EventLogEntryType.Error);
}
From the error message you have provided, it seems like request content is in application/json. ReadAsFormDataAsync() can only read content of type application/x-www-form-urlencoded.
In this case, you can use ReadAsAsync<> if you have the type you want to be deserialized defined or simply use ReadAsStringAsync<> if you just want to read the content as a string.
I want to update two different values with one ajax-response.
<span id="nr1">Change this</span>
<span id="nr2">and change this</span>
Now I can just change one value, I do like this:
document.getElementById('nr1').innerHTML = xmlHttp.responseText;
Is it possible to do something like this:
document.getElementById('nr1').innerHTML = xmlHttp.responseText1;
document.getElementById('nr2').innerHTML = xmlHttp.responseText2;
**** UPDATE ****
The response comes from php.
I'm totally new to JSON.
There are no responseText1 and responseText2 properties of an XMLHTTPRequest(which I assume your xmlHttp is), just responseText, so you have to return something parsable in that responseText field(like JSON). So you server may send back {"firstResponse":"value1","secondResponse":"value2"} and you can fill your fields from that JSON string. Use the json2.js library from json.org
<script type="text/javascript" src="json2.js"></script>
. . .
var theResponse = JSON.parse(xmlHttp.responseText);
document.getElementById('nr1').innerHTML = theResponse.firstResponse;
document.getElementById('nr2').innerHTML = theResponse.secondResponse;
EDIT:
In order to craft this JSON response from PHP you should use the PHP JSON libraries. There are several examples in the json_encode page that can get you started. The other code I posted(and that is posted in other responses) are all browser side javascript code.
$arr = array ('firstResponse'=>'value1','secondResponse'=>'value2');
echo json_encode($arr);
Place that code into your PHP script to generate the JSON string
{"firstResponse":"value1","secondResponse":"value2"}
Then the previously posted javascript code will parse that.
If you trust and control the server, just return a dictionary in JSON for the response and use it on the client side. So:
v = eval(xmlHttp.responseText);
document.getElementById('nr1').innerHTML = v['nr1']
document.getElementById('nr2').innerHTML = v['nr2']
As already said it would make sense to return your Ajax call as a JSON Object. I recommend the more secure JSONP call (don't know if you can use any library that supports this natively).
// Your script returns this
callback123(
{
"nr1" : "This is conten for nr1",
"nr2" : "Some content for nr2"
});
// JavaScript callback looks like this
function callback123(data)
{
for(var key in data)
document.getElementById(key).innerHTML = data[key];
}
use JSON.parse
link text