2

The following GET request works using jQuery:

$.ajax({
url: "https://yoda.p.mashape.com/yoda?sentence="+phrase,
headers: {"X-Mashape-Key": "superSecretKey", "Accept": "text/plain"},
success: function(data) {
        console.log(data);
      },
error: function(data) {
        console.log(data);
      }
})

But the adaptation that follows using Mithril will not work:

Yoda.submit = function (phrase) {
  console.log(phrase);
  return m.request({ 
  method: 'GET', 
  url: "https://yoda.p.mashape.com/yoda?sentence=" + phrase, 
  headers: {"X-Mashape-Key": "superSecretKey", 
          "Accept": "text/plain"}
  });
}

I've tried different variations after consulting the documentation at https://lhorie.github.io/mithril/mithril.request.html and searching for similar examples. I'm considering using 3rd party libraries but thought I'd try here before I go too far down the rabbit hole. The error message that I get when I try to make an AJAX request is that I'm missing the API key even though it's right there.

UPDATE:

I've since learned, in addition to the answer marked below, that Mithril automatically parses API responses as JSON. Since I'm getting back a string response from this API, I have to include in my m.request object the following entry:

deserialize: function(value) {return value;}

Deserialize tells Mithril to return the response value as-is, not as JSON.

Salman Oskooi
  • 366
  • 3
  • 8

1 Answers1

3

You need to use the config attribute:

m.request({method: 'GET', url: "https://yoda.p.mashape.com/yoda?sentence=" + phrase,
    config: function(xhr, options) {
        xhr.setRequestHeader("X-Mashape-Key", "superSecretKey")
        xhr.setRequestHeader("Accept", "text/plain")
    }}).then(function(data) {
        console.log('success: ', data)
    }, function(err) {
        console.log('error: ', err)
    })
Salman Oskooi
  • 366
  • 3
  • 8
fluminis
  • 3,575
  • 4
  • 34
  • 47
  • Just tried this and got an error in the console upon submitting the GET request to the API saying "Unexpected token H" from mithril.js:1126 and mithril.js:1067. Any ideas @fluminis? – Salman Oskooi Dec 16 '15 at 16:04
  • did you inspect everything in your console panel (parameters, headers, response)? did your server get called or the error is client side before the request actually be sent? – fluminis Dec 16 '15 at 16:39
  • Thanks for checking back! Yes I checked the Network tab in the console and it registers a status 200 for the xhr requests and at one point it returned with a 503 error from the API (which is not uncommon for this particular API) so I know the request is reaching the server; but no matter what there is a similar "Uncaught SyntaxError" that references the mithril library file. I learned that the accompanying "unexpected token" I mentioned in my last comment is always the first letter of the string that I pass in as input. @fluminis – Salman Oskooi Dec 17 '15 at 04:46