1

I'm trying to send a very simple Ajax POST request with basic authentication to a REST API. With Postman all seems to be OK, but when I do it through my webpage using jQuery, I'm getting a 401 error.

After several other attempts, currently this is my code:

$.ajax({
   type: 'POST',
   url: 'http://admin:admin@my_rest_api_url',
   data: { "name":"John","surname":"Doe" },
   crossDomain: true
});

Any suggestions are very welcome.

luthien
  • 1,285
  • 3
  • 15
  • 26
  • https://stackoverflow.com/questions/5507234/how-to-use-basic-auth-with-jquery-and-ajax – Zagonine Jun 09 '17 at 13:28
  • Use Postman for generate the c# code and put it on the question too. – Erick Lanford Xenes Jun 09 '17 at 13:28
  • Possible duplicate of [How to use Basic Auth with jQuery and AJAX?](https://stackoverflow.com/questions/5507234/how-to-use-basic-auth-with-jquery-and-ajax) – Erick Lanford Xenes Jun 09 '17 at 13:29
  • I'd tried that solution but didn't work either. Well, thanks @ErickLangfordXenes for the idea of generating the code from Postman, I didn't know there is this option. – luthien Jun 09 '17 at 13:40
  • This is the C# code: ```var client = new RestClient("http://my_rest_api_url"); var request = new RestRequest(Method.POST); request.AddHeader("postman-token", "57dc5705-5e51-88c4-2518-d790433d464b"); request.AddHeader("cache-control", "no-cache"); request.AddHeader("content-type", "application/json"); request.AddHeader("authorization", "Basic YWRtaW46YWRtaW4="); request.AddParameter("application/json", "{\n \"name\": \"John\",\n \"surname\": \"Doe\", ParameterType.RequestBody); IRestResponse response = client.Execute(request);``` (In the place of my_rest_api_url I have the real URL) – luthien Jun 09 '17 at 13:41
  • OK, silly from my part, I was trying to do the ajax request from a different domain and apparently this cannot work from a webpage. I'm closing the question. – luthien Jun 09 '17 at 15:46

0 Answers0