REST Call in MDriven, construct of HEADER? - mdriven

I am trying to model the following REST call in MDriven
jQuery.ajax({
type: 'POST',
url: 'http://server.net/api/server/search.php',
data: {
'apikey': xxxxxx,
'apiversion': '3',
'action': "search",
'type':'near',
'lat':'59.91673',
'long': '10.74782',
'distance': '2000',
'limit': '10'
},
success: printJsonResponse,
dataType: 'json'
});
The ViewModel would as I understand it be as follows:
But it is hard to test if this is the "same" (and it doesn't work)

One way to see what is actually sent is to send your data to some echo service that just returns what it gets.
I think there must be REST services for this. I googled "Rest echo service" and got this for example:
https://postman-echo.com/get?foo1=bar1&foo2=bar2
Try to send your request to https://postman-echo.com and then write out the result.

Related

500 error when trying to create page using REST API

I'm currently using Confluence server and I'm currently getting a 500 error when I try to create a new page using the REST API. I am currently using an HTML macro that makes GET & POST requests using the Fetch API. I currently have no issues when making GET requests, only issues with POST requests.
I tried researching the error and saw someone mention that they fixed it by turning off collaborative editing in the space, but in my case that is not an option. Anyone have an idea of what is causing this error?
function createPage() {
let url = "http://exampledomain:8090/confluence/rest/api/content/"
fetch(url, {
method: 'POST',
headers: {
'Authorization': 'Basic USER:PASS',
'Content-Type': 'application/json',
},
data: {
'type': 'page',
'title': "New Page",
'ancestors': [{ 'id': 97059352 }], // parent page id
'space': { 'key': "EXAMPLE_SPACE" },
'body': {
'storage': {
'value': "<h1>New Page!</h1>",
'representation': 'storage',
}
},
}
})
.then(response => console.log(response))
.catch(err => console.log(err.message))
}
I see invalid data structure:
'representation': 'storage', <== extra comma
}
}, <== another extra comma
}
Also double check with your programming language that you can use single quotes (') and that they are correctly transformed into double quotes ("). JSON (Jira REST API) accepts only double quotes for keys and string values.

Retrieving params with sinatra on form submit. Params is undefined

I am having trouble accessing params in Sinatra after submitting a form. This is my form:
function submitForm(e) {
e.preventDefault();
$.ajax({
type: 'POST',
url: '/mix_addresses',
//grab the inputs from address_section
//data: $('.add_address_section .add_address_field').map(function() { return $(this).val() }),
data: [1,2,3],
dataType: "json",
success: function(data) {
debugger;
}
});
}
And this is my endpoint:
require 'sinatra'
require 'jobcoin_client'
get '/' do
erb :add_coins
end
post '/mix_addresses' do
puts params
end
I'm getting to the endpoint, but the params are blank. Shouldn't it be [1,2,3]? Instead, it's:
{"undefined"=>""}
Anyone see what I'm doing wrong?
Several issues here :)
Sinatra configuration
Main problem is coming from the fact that Sinatra doesn't deal with JSON payloads by default. If you want to send a JSON payload, then the easiest solution will be :
To add rack-contrib to your Gemfile,
Then, require it in your sinatra app: require rack/contrib
And load the middleware that deals with this issue: use Rack::PostBodyContentTypeParser
And you should be good to go!
Source: several SO post reference this issue, here, here or here for instance.
jQuery ajax call
Also, note that there might be some issues with your request :
You'll need to use a key: value format for your JSON payload: { values: [1,2,3] }
You'll need to stringify your JSON payload before sending it: data: JSON.stringify( ... )
You'll need to set the request content type to application/json (dataType is related to the data returned by the server, and doesn't say anything about your request format, see jQuery ajax documentation for more details).
Eventually, you should end up with something like this on the client side:
function submitForm(e) {
e.preventDefault();
$.ajax({
type: 'POST',
url: '/mix_addresses',
contentType: 'application/json',
dataType: 'json',
data: JSON.stringify({ values: [1,2,3] }),
success: function(data) {
debugger;
}
});
}

How to cancel likes on other site

When you click the Like button https://graph.facebook.com/object_id/likes calls.
To cancel the Like what should I do?
I tried the following:
<code>
<script>
function doLike(objectId) {
$.ajax({
url: 'https://graph.facebook.com/'+objectId+'/likes',
type: 'post',
data: {
access_token: '....'
}
});
}
function doCancel(objectId) {
$.ajax({
url: '???',
type: 'post',
data: {
access_token: '....'
}
});
}
</script>
<input onclick="doLike('...')">Like</button>
<input onclick="doCancel('...')">Cancel</button>
</code>
This drove me nuts. Firefox/Chrome and probably everything else apparently won't allow HTTP DELETE ajax calls unless the host has previously communicated during the current request. So $.ajax{(type: 'delete', ... )} works for YOUR server url host but not anything else.
The workaround is something like:
$.ajax({
url: "https://graph.facebook.com/" + FB_ACTION_ID,
type: 'post',
data: { access_token: ACCESS_TOKEN,
'method': 'delete',
'_method' : 'delete' }
})
If you're looking for an API which allows you to remove a Like of a Facebook page, this is not possible.
If you're looking for an API to remove a Like of an object (via URL) - you can make a HTTP DELETE request to /LIKE_INSTANCE_ID which is the ID returned to your app when you posted the Open Graph like - otherwise it's not possible
You should be able to "unlike" an object ID simply by doing a HTTP DELETE. Using your code, it'd look something like this:
function doCancel(objectId) {
$.ajax({
url: 'https://graph.facebook.com/'+objectId+'/likes',
type: 'delete',
data: {
access_token: '....'
}
});
}
Alternatively, use the Facebook Javascript SDK, in which you can simply do:
FB.api("/" + objectId + "/likes", 'delete', callback);
where callback is the function to call when the unlike operation is complete.

How to read POST data with node.js without using express or connect

Edit
Make sure you don't juxtapose the request and response objects. things will be easier if you dont.
I am trying to POST data from a form with two inputs to a specific url node responds to.
Originally I was using the javascript xmlHTTPrequest object to send it. The data was received but node could never read the object I tried sending which was JSON format. Here is what it looked like when I converted it to a string:
{ output: [],
outputEncodings: [],
writable: true,
_last: false,
chunkedEncoding: false,
shouldKeepAlive: true,
useChunkedEncodingByDefault: true,
_hasBody: true,
_trailer: '',
finished: false,
socket:
{ _handle:
{ writeQueueSize: 0,
socket: [Circular],
onread: [Function: onread] },
_pendingWriteReqs: 0,
_flags: 0,
_connectQueueSize: 0,
destroyed: false,
errorEmitted: false,
bytesRead: 8442,
bytesWritten: 1669569,
allowHalfOpen: true,
writable: true,
readable: true,
This was not the full string. I switched over to use an ajax post request instead because I thought serializearray() might create a different format that node could read but it was the same. My server side code is essentially just:
function email(request, response)
form = '';
request.setEncoding("utf8");
request.on('data', function(chunk) {
console.log('data received');
form += chunk.toString();
});
request.on('end', function() {
console.log('done receiving post data');
});
My form looks like this
<form name="email" action="javascript:true;">
<input type="text" name="address" value="Enter your email address" onFocus="this.value=''">
<input class="special" type="text" name="honeypot">
<input type="submit" value="submit">
</form>
If I try parsing with JSON.parse, there is an error caused by unexpected o
If I try parsing with querystring, it returns an empty object
If I try something like console.log(form.address) the output is undefined but should be one of the values i submitted in the form.
my http server would route to /email and this is the function that responds to /email.
I checked and I know the on 'data' event has not expired because my code is set up to notify me of a 'data'event and I can see the event happening. Locally, this code works fine and I can read the data submitted but on the development server it just doesn't work.
I know people will say I should be using connect or express but let's just suppose that was not an option, how could I get node to correctly process this data? The jquery that submits the form is more or less standard. Many thanks!
EDIT:
Sorry, I thought the problem would be fixed as I noticed immediately the posted string was not JSON. Here is the code I am using to send the post.
$(document).ready(function() {
$("#email").submit(function(event) {
event.preventDefault();
var data = $(this).serializeArray();
$.ajax({
type: 'POST',
dataType: 'json',
url: '/email',
data: JSON.stringify(data),
success: function(msg) {
$("#aviso").html(msg);
}
});
});
});
Here is the string the data variable holds:
[
{
"name": "address",
"value": "foo#bar.com"
},
{
"name": "honeypot",
"value": "irobot"
}
]
This is valid JSON as per jsonlint. But still the same error when it reaches the server. Node handles the 'data' event and all is well until I try to parse the string, it causes an error undefined:1 unexpected o.
The data you're sending is not valid JSON, which requires that all object keys are double-quoted.

Facebook Javascript UI for Posting to Wall Just Flickers

I am trying to make a Facebook dialogue appear when the user completes an event and so I built this function.
function post_to_wall_popup(){
FB.init({ apiKey: 'Super Secret API Key' });
var publish = {
method: 'stream.publish',
attachment: {
name: 'XYZ',
caption: 'caption here',
description: ('description'),
href: 'url',
media: [{
type: 'image',
href: 'url',
src: 'xyz.gif'
}]
},
action_links: [{ text: 'XYZ', href: 'url' }]
};
FB.ui(publish,null);
}
I have tried a few different examples that are supposed to have similar results but on each one all I get is the dialog box with "Loading.." for a split second, then it disappears.
Has anyone else ever come across a similar problem?
Make sure that fb-root is defined & visible.