How to debug the No header. Access-Control-Allow-Origin is present in the requested resource.

I get this error displayed in the browser console:

XMLHttpRequest cannot load http: // localhost: 8080 / api / login . The requested resource does not have an Access-Control-Allow-Origin header. The origin of http: // localhost: 9009 'is therefore not allowed.

I use the following environments:

  • Backend - Spring Download
  • Front End - Angularjs
  • Web Server - Grunt

On the server, I already define the headers in the request and response as:

public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest httpRequest = (HttpServletRequest) request;
        HttpServletResponse httpResponse = (HttpServletResponse) response;

        httpResponse.setHeader("Access-Control-Allow-Origin", "*");
        httpResponse.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE,PUT");
        httpResponse.setHeader("Access-Control-Max-Age", "3600");
        httpResponse.setHeader("Access-Control-Allow-Headers", "x-requested-with,Authorization, Content-Type");

        if (httpRequest.getMethod().equals("OPTIONS")) {
            httpResponse.setStatus(HttpServletResponse.SC_ACCEPTED);
            return;
        }
}

"Access-Control-Allow-Origin" , .

:

enter image description here

+4
4

CORS ( Cross Origin) -. . .

:

Access-Control-Allow-Origin: *

, CORS

CORS , , .

API curl

URL- API , cURL - . (Laravel + AngularJs).

cURL.

Laravel-PHP, , , .

:

public function curlRequester($url,$fields)
    {
        // Open connection
        $ch = curl_init();

        // Set the url, number of POST vars, POST data
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true );

        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $fields);

        // Execute post
        $result = curl_exec($ch);

        // Close connection
        curl_close($ch);

        $result_json_decoded = json_decode($result, true);


        return $result_json_decoded;
    }

public function login()
{

    // set POST params
    $fields = array(
        'username' => Input::get('username'),
        'password' => Input::get('password')
    );
    $url = 'http://www.this-is-api-url.com/login';

    $result = $this->curl->curlRequester($url,$fields);

    return response()->json($result);

}

Angular

$scope.authCheck = function(){

        $http({
            url:'http://www.our-project-url/login',
            method:"post",
            data:{"username": "rameez", "password":"rameezrami"}
        })
        .success(function(response) {
            if(response.status==1){
                $location.path("/homepage");
            }else if(response.status==0){
                $scope.login_error_message_box = true;
                $scope.login_error_message_text =response.message;
            }

        });

    }
+1

CORS / CORS. , .

4.2, Spring Framework CORS - . .

Spring Boot, 1.3.0 ( ) .

+1

Your filter is right, you must enable your filter as a component and place it where it can be scanned with spring

@Component
public class CORSFilter implements Filter{

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest req, ServletResponse res,
            FilterChain chain) throws IOException, ServletException {

        HttpServletResponse response = (HttpServletResponse) res;
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
        response.setHeader("Access-Control-Max-Age", "3600");
        response.setHeader("Access-Control-Allow-Headers", "x-requested-with");
        chain.doFilter(req, res);

    }

    @Override
    public void destroy() {

    }

}
0
source

You also need to do an update in angular code to enable CORS through AJAX.

myApp.config(['$httpProvider', function($httpProvider) {
        $httpProvider.defaults.useXDomain = true;
        delete $httpProvider.defaults.headers.common['X-Requested-With'];
    }
]);

If the above does not work, you may also need to add the following:

myApp.all('/*', function (request, response, next) {
    response.header("Access-Control-Allow-Origin", "*");
    response.header("Access-Control-Allow-Headers", "X-Requested-With");
    response.header("Access-Control-Allow-Methods", "GET, POST", "PUT", "DELETE");
    next();    
});

As @Marged noted, you want to be careful about "*", and I highly recommend replacing it with your domain (s).

0
source

Source: https://habr.com/ru/post/1611417/


All Articles