1

I've been using Postman to test my REST API (written in Go). Now is the moment of truth, connecting to the front end and I've hit a hiccup. I'm using jQuery.ajax to send a GET to my server, which should then send me back the response.

Note: Going to postman and sending a GET request to http://REMOTE_IP:8000/users/ returns the information I'm looking for, an array of User objects (JSON). It confuses me that it would work for Postman, but not jQuery.

jQuery Get

$.ajax({
    url: "http://REMOTE_IP:8000/users/",
    type: "GET",
    dataType: 'jsonp',
    contentType: 'application/json',
    success: function(data) {
        console.log(data);
    },
    error: function(jqXHR, status, err) {
        console.log(jqXHR);
        console.log(status);
        console.log(err);
    }
});

Go Backend

func GetUsersRoute(w http.ResponseWriter, r *http.Request) {
    var queryResult []models.User

    queryErr := Config.Users.Find(bson.M{}).All(&queryResult)
    resultsJSON, jsonErr := json.Marshal(queryResult)

    handleQueryAndJsonErrors(w, queryErr, jsonErr)

    // added these for cors, not sure they do anything helpful
    w.Header().Set("Content-Type", "application/json; charset=UTF-8")
    w.Header().Set("Access-Control-Request-Headers", "*")

    w.WriteHeader(http.StatusOK)
    w.Write(resultsJSON)
}

I also have a logger attached to my go backend, and here are the request method and request URI that are printed out when I make the request:

GET /users?callback=jQuery223019655483671137586_1461946990647&_=1461946990648

Here are some articles I found useful:
The data which jquery $.ajax function return could not be parse to json

https://github.com/codegangsta/martini-contrib/blob/master/cors/cors.go

https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS#Access-Control-Allow-Methods

Here are the errors returned with jQuery's err callback: enter image description here

What could be going wrong?

4
  • 1
    Your datatype for your ajax call is jsonp? Are you intending to do that?
    – tier1
    Apr 29, 2016 at 16:50
  • 1
    Is there any particular reason you're using jsonp instead of json as datatype? jsonp expects a callback to be fired and, as far as I can see, neither your client nor your server sides are ready to handle that. Perhaps you just need to perform a regular post request using json as datatype instead or are you trying to avoid cross-domain issues?
    – briosheje
    Apr 29, 2016 at 16:50
  • Perhaps you should check this:stackoverflow.com/questions/17036365/…
    – briosheje
    Apr 29, 2016 at 16:58
  • The reason I use jsonp is because of CORS. I get '.. response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin REMOTE_IP ...'
    – shane
    Apr 29, 2016 at 17:34

2 Answers 2

0

First check whether your server can handle JSONP requests by using following tests.

http://REMOTE_IP:8000/users?callback=myFunction

The response instead of this (it will look like this if it doesn't support JSONP):

{ "thing": "value" .... }

Should look like this (again, if it supports JSONP):

myFunction({ "thing": "value" .... });
0

# Answer

I found a nice go library that handles the cross-origin problems I was having, meaning I didn't have to rely on jsonp. Here's the revised go code:

Using the CORS Handler

handler := cors.Default().Handler(r)
err := http.ListenAndServe(port, handler)

if err != nil {
    panic(err)
}

Revised handler

func GetUsersRoute(w http.ResponseWriter, r *http.Request) {
    var queryResult []models.User

    queryErr := Config.Users.Find(bson.M{}).All(&queryResult)
    resultsJSON, jsonErr := json.Marshal(queryResult)

    handleQueryAndJsonErrors(w, queryErr, jsonErr)

    w.Header().Set("Content-Type", "application/json; charset=UTF-8")
    w.WriteHeader(http.StatusOK)
    w.Write(resultsJSON)
}

Calling from the frontend

var extension = 'users/',
    requestPath = serverAddress + extension;

$.ajax({
    url: requestPath,
    type: 'GET',
    dataType: 'json',
    contentType: 'application/json',
    success: successCall,
    error: failCall
});

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.