0

I use the Chrome extension Postman to generate code for POST and GET requests with the appropiate headers, but after hours of working with this I see I'm gonna need help. It works perfectly in Postman, but the Javascript code it provides is somehow wrong.

If I make the request without the Authentication header I get a GET 401 - Unauthorized.

If I make the request with the Authentication header I get a OPTIONS 401 - Unauthorized.

        $.ajax(
        {
        "async": true,
        "crossDomain": true,
        "url": "http://mywebservice.com/example.php?key=myValue",
        "method": "GET",
        "headers": 
            {
                "authorization": "Basic YWRtaW39NjU1YzVlMWM="
            }
        })

Can anyone explain why I get a 401 Options when I use the correct Authorization header? I have also tried using btoa(username + ":" + password) - same result.

user3296337
  • 107
  • 10

1 Answers1

1

The browser is stopping you from making a cross-domain request to protect you from security vulnerabilities.
(This doesn't happen in postman, because postman is a browser extension, and thus has different permissions than a standard webpage.)

There are a few ways around this :
1. If both domains are under your control, then make use of the Access-Control-Allow-Origin HTTP header
2. Use jsonp to make the call

gillyb
  • 8,760
  • 8
  • 53
  • 80
  • You can't set custom headers with JSONP. Using Access-Cointrol-Allow-Origin won't prevent the OPTIONS request from being made. – Quentin Jul 29 '15 at 12:00
  • Thank you very much gillyb! I added "dataType": "jsonp" and it works perfectly now! Thanks a lot for your help :) – user3296337 Jul 29 '15 at 12:05