0

I am trying to call servlet using ajax on click event. And from that servlet I am calling google auth end point. I tried set header to the servlet I am calling but I an not able to get rid of this error

XMLHttpRequest cannot load https://accounts.google.com/o/oauth2/auth?client_id=2536-a…nid%20profile%20email&state=F1BFD3804&display=popup. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8080' is therefore not allowed access.

Here is the code

$.ajax({
                type: "GET",
                url: "/url-for-servlet",
                dataType: "jsonp",
                contentType:    'application/json',
                error: function (jqXHR, textStatus, errorThrown) {
                    console.log(jqXHR)
                },
                success: function (data) {
                    alert("yippy");
                    console.log(data);

                }
            });

On servlet I added to response

response.addHeader("Access-Control-Allow-Origin", "*");
        response.addHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
        response.addHeader("Access-Control-Max-Age", "3600");
        response.addHeader("Access-Control-Allow-Headers", "x-requested-with");

Any idea what I am missing here? Thanks for the help.

VVN
  • 1,607
  • 2
  • 16
  • 25
user557657
  • 856
  • 1
  • 12
  • 35
  • Those headers need to be set by the target URL (accounts.google.com thus). The inability to do should already have implied that you're not allowed to do those things with the target service. Look for a different solution, usually based on their own API documentation. Your question is however strange as the error is not caused by the code posted so far. Perhaps you oversimplified/omitted too much? – BalusC Mar 05 '16 at 12:46

2 Answers2

0

This is a standard security restriction : JS cannot make requests to domains other than their own. So you have an application on localhost making Ajax calls to an application on accounts.google.com - not allowed by default.

See this question

Community
  • 1
  • 1
NickJ
  • 9,380
  • 9
  • 51
  • 74
0

AJAX usually doesn't allow to call other domain API from it. It is called CSRF attack. The solution for you is, Post the data to your server servlet and do the action required there in the backend(Servlet).

Aravindhan
  • 3,566
  • 7
  • 26
  • 42