jquerypostman

Replicating Simple Postman API Call With Raw Data in jQuery


I have this simple API call that is working in POSTMAN:

enter image description here

enter image description here

Real simple. Works perfectly.

However, I've tried to replicate this in jQuery like follows:

$.ajax({
    url: "https://example.us-east-1.amazonaws.com/prod",
    type: "POST",
    contentType: "application/json",
    data: {
        id_api: "catalogo_get_categorias"
    },
    success: function(results){
        console.log(results)
    },
    error: function(err) {
        console.log(err)
    }
});

But it keeps coming back with 500 error.

Any ideas?

Edit:

The console produces the following error when I have the Chrome CORS extension disabled

enter image description here

And with the CORS plugin enabled this is the output enter image description here


Solution

  • Postman isn't bound to the same-origin policy like your browser (Chrome) is. If the API endpoint that you're requesting - https://example.us-east-1.amazonaws.com/prod - doesn't respond with a CORS header like Access-Control-Allow-Origin: *, you'll hit the exception that you've posted.

    To solve the problem, your options are basically:

    1. Add the CORS header(s) to the response, if AWS allows.
    2. Route the request through a proxy server, so that the server makes the actual request to AWS, and isn't bound to the same-origin policy.

    Also be sure that the $.ajax() request sets the appropriate headers by using pertinent config object properties. For example, you may need to set the xhrFields.withCredentials property on the config object you pass to $.ajax():

    $.ajax({
      url: "https://example.us-east-1.amazonaws.com/prod",
      type: "POST",
      contentType: "application/json",
      xhrFields: {
        withCredentials: true
      },
      data: {
        id_api: "catalogo_get_categorias"
      },
      success: function (results) {
        console.log(results);
      },
      error: function (err) {
        console.log(err);
      }
    });