Sunday, 4 June 2017

Unexpected token ":" with JSON returned from node and express

I'm building a small web service with Node.js and Express, and I'm running into a bit of a problem. Everything seems to work perfectly fine, until I true to use it with Ajax in a browser. If I run it in Postman, I get:

{
  "status": "ok",
  "data": [
    {
      "GUID": "2f779770-9e1c-415f-9518-ff7fd7d6631c",
      "name": "The Revolver",
      "description": "Rye heavy bourbon, coffee liqueur, orange bitters, orange garnish.",
      "active": 1,
      "categories": [
        "94162f2e-3b2f-4521-a543-068ed6c81011"
      ]
    },
    {
      "GUID": "f05a33ad-e684-4ae0-804c-0c1a61b9945d",
      "name": "Jack Rose",
      "description": "Laird's Applejack, Grenadine, Lemon, Peychaud's bitters, Lemon twist",
      "active": 1,
      "categories": []
    }
  ]
}

Headers includes Content-Type →application/json; charset=utf-8

But when I make the ajax call Chrome says "Uncaught SyntaxError: Unexpected token :"

I'm using res.json({status: "ok", data: result}) to return the response from Express. I've also tried res.setHeader('Content-Type', 'application/json'); with no luck.

Any ideas?

Edit: here's the ajax call:

function getDrinks(){
  $.ajax({
    url: serviceURL + "getDrinks",
    type: "GET",
    dataType: "jsonp",
    success: function(result){
      if (result.status=="ok"){
        var tableHTML=""
        for (var i = 0; i < result.data.length; i++) {
          var drink=result.data[i]
          tableHTML+="<tr><td>"+drink.name+"</td></tr>"
        }
        tableHTML="<table>"+tableHTML+"</table>"
        $("#drinksContainer").html(tableHTML);
      }
    }
  })
}



via effendo

No comments:

Post a Comment