Skip to content
shiffman edited this page Dec 9, 2014 · 7 revisions

GET requests

HTTP requests can be GET or POST. A GET request is something you do all the time but asking for a URL in your browser. It might look something like:

http://server.com/path/?param=value&anotherparam=value

We have also been doing this already in p5 with loadStrings(), loadJSON(), etc. Behind the scenes, assuming a URL is passed in, a GET request is made to a server.

p5 also has a special new function for making a generic GET request. This can be useful if you aren't getting a specific kind of data back (or don't need any data back). In addition if you don't want to form the query String yourself (?param=value&anotherparam=value) p5 will do it for you with an object you pass in. It looks like this.

httpGet(url, params, callback)

So an example might be:

var params = {
  username: 'Dan',
  num: 99
}
  
httpGet('http://mywebapp/something', params, finished);

function finished(response) {
  console.log(response);
}

POST requests

A POST is similar to a GET however the data is obscured. This is useful when you need to send a large dataset or if you are sending private information like a password. You cannot make a POST directly from the URL but rather have to execute some code that posts the data. Here's how this would look in p5.

var data = {
  username: 'Dan',
  num: 99
}
  
httpPost('http://mywebapp/something', data, finished);

function finished(response) {
  console.log(response);
}

This works nicely with servi as you can just specify a route and dump the data directly into a database. For example:

// A database
var dbase = useDatabase("yourdb");

// A route for saving data
route('/save', saveData);

function saveData(request) {
  // The data comes in the 'fields' object
  var data = requests.fields;
  dbase.add(data);

  request.respond('Thanks for your data!');
}

Here's the full example

Clone this wiki locally