1

How can I append ?apiKey=12341234 onto every ajax request for fetch, create, save etc... The MongoLabs api requires this and i've been struggling to get this to work fully.

I'm currently working though a backbone tutorial screencast and the author is using a php framework to create an api for the backbone app. I thought I was going to be smart by using MongoLabs free rest api... and then I burnt up 2 days reading docs and trying to make it work.

The closest i've come is to pass in the param when fetch is called (doesn't work with create): Fetch Backbone collection with search parameters

{ data: $.param({'apiKey':'50b28f80e4b0995a3f4312a0'}) }

Working url:
https://api.mongolab.com/api/1/databases/bbone_rest/collections/tasks/2/?q=&apiKey=50b28f80e4b0995a3f4312a0

Code on jsfiddle: http://jsfiddle.net/py4Pv/

# Encapsulate classes
window.App =
  apiKey: { data: $.param({'apiKey':'50b28f80e4b0995a3f4312a0'}) }
  Models: {}
  Views: {}
  Collections: {}



# The model for a single task
class App.Models.Task extends Backbone.Model
  #override backbones 'id' attr to match mongo's '_id' attr
  idAttribute: "_id"
  defaults:
    title: "None provided"
    completed: 0


# The model for a collection of tasks
class App.Collections.Tasks extends Backbone.Collection
  model: App.Models.Task
  url: 'https://api.mongolab.com/api/1/databases/bbone_rest/collections/tasks/'





##################### Views, prob not important ########################  


# View for a list of tasks
class App.Views.Tasks extends Backbone.View
  tagName: 'ul'

  initialize : () ->
    @collection.on 'add', @addOne

  render: ->
    # Cycle through each task in collection and call @addOne
    @collection.each @addOne
    return this

  addOne: (task) =>
    task = new App.Views.Task({ model: task })
    @$el.append( task.render().el )


# View for a single task unit
class App.Views.Task extends Backbone.View
  tagName: 'li'
  render: ->
    @$el.html( this.model.get('title'))
    return this

* Edit * Headers info when adding : $.ajaxSetup({ data: { key: "value"} after a task.destroy()

Request URL:https://api.mongolab.com/api/1/databases/bbone_rest/collections/tasks/1
Request Method:OPTIONS
Status Code:400 Bad Request

Request Headersview source
Accept:*/*
Accept-Charset:ISO-8859-1,utf-8;q=0.7,*;q=0.3
Accept-Encoding:gzip,deflate,sdch
Accept-Language:en-US,en;q=0.8
Access-Control-Request-Headers:origin, accept
Access-Control-Request-Method:DELETE
Connection:keep-alive
Host:api.mongolab.com
Origin:null
User-Agent:Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_2) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.95 Safari/537.11

Response Headersview source
Connection:close
Content-Length:50
Content-Type:application/json;charset=utf-8
Date:Fri, 30 Nov 2012 06:42:57 GMT
Server:Apache/2.2.22 (Ubuntu)
Community
  • 1
  • 1
SkinnyG33k
  • 1,721
  • 4
  • 23
  • 30

3 Answers3

2

You can specify a function for the url property of the model/collection -- that way you should be able to append the api in the query string each time. Ie, something like (sorry, I'm unsure of Mootools syntax):

url: () => 
   return 'https://api.mongolab.com/api/1/databases/bbone_rest/collections/tasks/' + this._id + '?api=' + App.apiKey
McGarnagle
  • 101,349
  • 31
  • 229
  • 260
  • This is close, but if I put this in the model, it is overridden from the collection url, if I delete the collection url, then tasks.fetch() conmplains from a lack of collection url. If I put it in just the collection, then it has an undefined from the model id: https://api.mongolab.com/api/1/databases/bbone_rest/collections/tasks/undefined?apiKey=50b28f80e4b0995a3f4312a0 – SkinnyG33k Nov 30 '12 at 07:17
  • 1
    @SkinnyGeek1010 maybe I'm missing something, but it seems like you should be able to put the URL function in both the collection and the model. The collection methods like `fetch` should use the collection URL, and likewise for the model collections like `save` and `destroy`... no? – McGarnagle Nov 30 '12 at 07:51
  • you can but then it won't automatically create an id for you. If you manually create an id for each instance, then it will work to use get('_id') in the url string. I've given up an decided to roll my own api with node/express/mongodb lol. – SkinnyG33k Dec 08 '12 at 00:39
0

Have you tried:

$.ajaxSetup({
  data: {
    key: "value"
  }

This will add the key param to every ajax request. Having data declared in the ajaxSetup is cumulative.

Jake Dempsey
  • 6,264
  • 1
  • 30
  • 25
  • I tried adding this at the beginning and end of the file with no success. (using task.destroy). It works client side but doesn't append the url. ( I added the headers info above) – SkinnyG33k Nov 30 '12 at 06:45
  • edit, it does work with fetch (allowing me to ommit passing in the api key on fetch). But it still does not work with .destroy()... not sure why. – SkinnyG33k Nov 30 '12 at 07:10
0

Best way to handle this is ajaxPrefilter

var api_key = '465456132456'
$.ajaxPrefilter( function( options, originalOptions, jqXHR ) {
  options.url = 'YOUR_URL' + options.url + '?key=' + api_key;
});
Severian
  • 325
  • 3
  • 7