How to properly read POST params with express? - express

My node app is supposed to POST to an external server, so I'm playing with request from NPM. I want to verify it's working, but I'm not entirely sure I'm doing that right.
I've tried both of these methods
request({
url: url,
method: 'POST',
form: { a: 1}
}
request({
url: url,
method: 'POST',
json: true,
body: { a: 1}
}
In my test when I hit my own server, req.body shows the right object when I do json true. However that just means I'm passing a JSON header. The API I actually need to hit is expecting a normal POST, not JSON.
So when I try to verify that request is working right when I use form, my server says req.body is an empty object.
EDIT
I am posting to external API fine using form, but on my own server, express is leaving request.body as empty object.

See if this works for you:
request.post('http://service.com/upload').form({key:'value'})

Related

How to call Phishtank API to get JSON response?

It was really painful to find how to call Phishtank API here.
After a lot of searching I was able to find how to call the API. Below is a sample call,
https://checkurl.phishtank.com/checkurl/index.php?url=http://auto.smtpsystems.net/&format=json
But the problem with the above call is that it gives the response in XML format whereas I want the response in JSON format.
Any kind of help will be greatly appreciated.
The problem is that you are making an HTTP GET request. And this method accepts an HTTP POST request
//Custom your request
var requestOptions = {
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
url: "https://checkurl.phishtank.com/checkurl/",
method: 'POST',
json: true,
body: {
url: The URL to check(urlencoded or base64 encoded),
format: 'json',
app_key: Your application key
},
};
//Do the request
request.post(requestOptions, function callback(err, httpResponse, json) {
//Here you json
})
Make sure to use https instead of http in the endpoint url, although in Documentation http is given(as of writing this).
Use HTTP POST request not HTTP GET.
And format is in quotes(double preferred)
# Python implementation
endpoint = "https://checkurl.phishtank.com/checkurl/"
url = "http://www.travelswitchfly.com/"
response = requests.post(endpoint, data={"url": url, "format": "json"})
You have to specify the url, format, and the app_key in the body of the POST request.
I was trying to implement their API in my android application with the help of Retrofit. Their documentation is outdated. After spending 3 hours I come to know a few things.
use this URL https://checkurl.phishtank.com/checkurl/ (do not use URL with http://)
use the below interface for retrofit GET request. it does not work with #Query and it requires #FormUrlEncoded
#FormUrlEncoded
#GET("https://checkurl.phishtank.com/checkurl/")
fun findPhishing(
#Field("format") format: String,
#Field("url") url: String
): Single<Response>

submitting a form to the server as json

I am trying to submit a form to the server with the params in JSON.
form.submit({
url:'JSONSaveEntry',
method:'POST'
});
but it sends everything as form-www-urlencoded.
I already checked that no field has isFile set to true (but then, it would send as multipart-formdata) and that standardSubmit is false.
I also tried to use
Ext.Ajax.request({
url:'JSONSaveEntry',
method:'POST',
params:form.getValues()
});
and
Ext.Ajax.request({
url:'JSONSaveEntry',
method:'POST',
params:Ext.encode(form.getValues())
});
Every submission is done as form-www-urlencoded, although the docs clearly state "Performs a Ajax-based submission of form values (if standardSubmit is false)". But then, this sentence is already proven wrong because whenever a file field is in the form, the form is submitted as multipart.
So, does anyone know how I can get the form submitted as JSON?
Possibility 2: I know that it works if I submit a model via model.save(), but how would I create a model from a form on-the-fly (without hardcoding the fields twice)?
I think below would solve your purpose.
Ext.Ajax.request({
url:'JSONSaveEntry',
method:'POST',
headers: { 'Content-Type': 'application/json' },
jsonData : JSON.stringify(form.getValues()),
success : function(response){ console.log("response from server")},
failure : function(error){console.log(error)}
});

dojo/request/xhr returning xml instead of json

I'm using a simple dojo xhr request:
require(["dojo/query", "dojo/on", "dojo/dom-style", "dojo/request/xhr", "dojo/domReady!"],
function (query, on, domStyle, xhr) {
xhr("api/products", {
handleAs: 'json'
}).then(function (data) {
console.log('GOT DATA FROM DOJO XHR', data);
}, function (err) {
console.log('ERROR FROM DOJO XHR', err);
});
}
);
This works fine, but the data returned is as XML not JSON.
However, the same call in jQuery returns the data in JSON.
When I look at the headers, for the jQuery call it shows: Content-Type application/json; charset=utf-8, but for the dojo call it shows: Content-Type application/xml; charset=utf-8
I also added:
headers: { "Content-Type": "application/json; charset=uft-8" }
to the xhr parameters, but still no luck, it still returns xml.
What gives? How do you tell dojo xhr to handle it as json? I'm using dojo 1.8.3.
the server doesnt behvae like that by itself. check using firebug what dojo and jquery are requesting when they do a xhr. there has to be a param that tells the server that it is dojo or jquery. change that parameter.
dojo and jquery are the same, they are based on js and they both use xhr. please consider posting the exact request information for both.
Fixing server side works, but this is a band-aid solution. Server responds correctly to what it sees in the Accept header. Even if in Dojo xhr call you specify 'application/json', for some reason Firefox replaces it with 'text/html,application/xhtml+xml,application/xml;q=0.9,/;q=0.8' or something similar. As a result .NET sends back XML instead of JSON. Does not happen in other browsers.
I am still looking at how to fix it in a correct way.
Update: I think I have an answer, but not sure why it fixes it. If I set headers value in xhr request like the following, then everything works in Firefox:
headers: {
'Content-Type': 'application/json; charset=utf-8',
'Accept': 'application/json'
}
If I use double-quotes, then these headers are not transmitted to the server and XML is returned instead.
Ok, found the problem of why it's happening, but not the root cause.
I'm using the web api with asp.net mvc4 for the json service. It turns out somehow that for dojo the service is returning xml but for jQuery it returns json.
So, if it interests anyone else, how I fixed it, is that in WebApiConfig I removed xml as a supported return type:
var appXmlType = config.Formatters.XmlFormatter.SupportedMediaTypes.FirstOrDefault(t => t.MediaType == "application/xml");
config.Formatters.XmlFormatter.SupportedMediaTypes.Remove(appXmlType);
Since I"m only interested in JSON, this is ok for me, but if you need to support both, then you may have to look deeper.
So, to summarize, the issue is not really a dojo xhr issue, i.e, not a client issue, it's a server issue not handling the request properly.
Hope it helps anybody else.

OAuth Post Request Failing

I've got everything working up until Step 2 of the OAuth process where you request the actual token. I'm using a very simple jQuery Post request and constantly getting Access Control Origin errors. I've tried contentType: 'application/json' and everything else I know to try.
It's just not working and I'm not sure the problem. I've confirmed all the variables are set properly before the request. Simple post request...
var url = 'https://[STORENAMEVARIABLE].myshopify.com/admin/oauth/access_token';
var data = JSON.stringify({ client_id: apiKey, client_secret: secret, code: code });
$.ajax({
type: 'POST',
url: url,
data: data,
success: function(data) {
debugger;
},
error: function(data) {
debugger;
}
});
Any ideas what I'm doing wrong?
You need to make your OAuth requests from a server. This is the Javascript cross-domain security kicking in.
If you are using Rails you can use omniAuth and it'll take care of the whole OAuth dance for you. Otherwise you'll have to search around but most popular language have an OAuth library that you can just plug in.

Adding a social tag to a page

In SharePoint when you click on the "I Like It" icon, it sends json to this URL
"_vti_bin/socialdatainternalservice.json/AddQuickTag"
So I wrote a custom script which sends JSON data
$("a").click(function(){
$.ajax({
type: "POST",
url: "/_vti_bin/socialdatainternalservice.json/AddQuickTag",
data: '{"targetPage":"http://url/calendar.aspx","title":"Documents - All Documents","quickTagId":0}',
contentType: "application/json",
success: function(msg){
alert(msg);
}
});
return false;
});
I get an error which simply says "There was an error processing the request." and the error in the log file says "Request format is unrecognized for URL unexpectedly ending in '/AddQuickTag'."
Is it possible to write a custom script which will post JSON data to this URL and have SharePoint tag a page?
These are the calls that are made for the I Like it functionality
/vti_bin/socialdatainternalservice.json/GetNormalizedPageUrl
Post
{"pageUrl":"http://<web app name>/SitePages/Home.aspx"}
Returned
{"d":"http://<web app name>/"}
/vti_bin/socialdatainternalservice.json/AddQuickTag
Post
{"targetPage":"http://<web app name>/","title":"Home - Home","quickTagId":0}
Returned
{"d":null}
I think you need to do the GetNormalized call first.