0

I am a bit confused about how to use get() and post() in query to get data from a node.js server if the node.js server parses data from a json file and serves the html at a localhost:3000, will the client side code look something like this:

$(document).ready(function() {
$.ajax({
    url: 'localhost:3000/',
    dataType: "json",
    success: function(data) {
        $("#test").append(data);
    },
    error: function(jqXHR, textStatus, errorThrown) {
        alert('error ' + textStatus + " " + errorThrown);
    }
});
});

I am confused about what datatype etc means.

1 Answer 1

2

From jQuery documentation

dataType (default: Intelligent Guess (xml, json, script, or html)) Type: String The type of data that you're expecting back from the server. If none is specified, jQuery will try to infer it based on the MIME type of the response (an XML MIME type will yield XML, in 1.4 JSON will yield a JavaScript object, in 1.4 script will execute the script, and anything else will be returned as a string).

So the code you're showing expects the server to respond a json string, not HTML. If you remove dataType jQuery will 'guess' the response content as explained, which is what I believe you should do. Also the .ajax method defaults to making GET calls. If you want to POST change your code to the following - assuming you're using a jQuery version >= 1.9:

$(document).ready(function() {
  $.ajax({
      url: 'localhost:3000/',
      method: "POST",
      success: function(data) {
          $("#test").append(data);
      },
      error: function(jqXHR, textStatus, errorThrown) {
          alert('error ' + textStatus + " " + errorThrown);
      }
  });
});

You can also use jQuery's shorthand methods for GET and POST instead of the low-level .ajax method.

Sign up to request clarification or add additional context in comments.

6 Comments

Thanks for your helpful answer!
If you feel it's right, please mark it as the answer.
just a follow-up, does this mean that if i want to invoke a restful api from the server, i will have to change the url to localhost:3000/GET/action/1 ?
If GET is part of the url, then yes. But usually the http verb is not part of the url, since you would be able to POST to that url as well.
so where do we use the word GET then? sorry for the stupid question. the resources I have seen online for rest api design say GET /dogs/123/ .... so do they mean that you never actually use GET when you type in the URL?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.