CORS problem on localhost when calling REST service from angularjs

I am learning angularJS and trying to implement it in my application.

I have a RESTful WCF service hosted on local IIS. It has a GET method defined to get the list of documents: http: // localhost: 70 / DocumentRESTService.svc / GetDocuments /

Now I am trying to use this service in my angular application and display data. The following is the code: HTML:

<html>
    <script src="../../dist/js/angular/angular.min.js"></script>
    <script src="../../assets/js/one.js"></script>
    <body ng-app="myoneapp" ng-controller="oneAppCtrl">
                {{"Hello" + "AngularJS"}}
        <hr>
        <h1> Response from my REST Service </h1>
        {{hashValue}}

        <hr>
        <h1> Response from w3school REST Service </h1>
        {{names}}


    </body>
</html>

JS:

angular.module('myoneapp', [])
    .controller('oneAppCtrl', function($scope,$http){
        $scope.documentValue = {};

        $http({method: 'GET',
                url: 'http://localhost:70/DocumentRESTService.svc/GetDocuments/',
                headers:
                        {
//                          'Access-Control-Allow-Origin': 'http://localhost'
                        }                   
               })
            .success(function(data){ alert('Success!'); $scope.documentValue=data;})
            .error(function(data){ alert('Error!'); $scope.documentValue=data; alert('Error!' + $scope.documentValue);})
            .catch(function(data){ alert('Catch!'); $scope.documentValue= data;});

        $http.get("http://www.w3schools.com/angular/customers.php")
            .success(function(response) {$scope.names = response.records;});            
});

The strange behavior of this code works fine in IE11, while it does not run in Chrome / Firefox.

The answer below is in chrome: (for my REST service), while the REST service from w3schools worked just fine.

{ "": , "": 0, "": { "": "GET", "transformRequest": [] "transformResponse": [], "URL":" http://localhost:70/DocumentRESTService.svc/GetDocuments/", "headers": { "Accept": "application/json, text/plain,/" }}, "statusText": "" }

.

  • [ Chrome: ]

XMLHttpRequest http://localhost:70/DocumentRESTService.svc/GetDocuments/. "Access-Control-Allow-Origin". ://' .

  • [ Chrome: ]

XMLHttpRequest http://localhost:70/DocumentRESTService.svc/GetDocuments/. "Access-Control-Allow-Origin". http://127.0.0.1:55969 ', , .

  • [ Firefox:]

: http://localhost:70/DocumentRESTService.svc/GetDocuments/. , CORS.

:

  • localhost ? , ?
  • - , , ? , WCF? ( - )
  • JSONP ? , ? , ? ( , , resarching , , .)

.

P.S:

  • IDE: Brackets, .
  • AngularJS v1.4.3
  • stackoverflow, (CORS), $resource, $provider, $config. . - .
+4
4

. - , , .

Ques1.

'Why is localhost or my machineName considered to be a cross-domain request?'

as @charlietfl : - .

Ques2.

'Are there any changes required to do at my service end to enable this behavior?'

! .

Access-Control-Allow-Origin: *

. * . , , WCF REST. () , CORS .

WebOperationContext.Current.OutgoingResponse.Headers.Add(
"Access-Control-Allow-Origin", "*" ); WebOperationContext.Current.OutgoingResponse.Headers.Add(
"Access-Control-Allow-Methods", "POST" ); WebOperationContext.Current.OutgoingResponse.Headers.Add(
"Access-Control-Allow-Headers", "Content-Type, Accept" );

CORS /.

Ques3.

JSONP GET , , CORS. ( , Wiki stackoverflow ).

, . , CORS.

+4

CORS, Ionic ( ) - Node.JS( ).

: Chrome AllowControlAllowOrigin.

https://chrome.google.com/webstore/search/cross%20origin?utm_source=chrome-ntp-icon&_category=extensions

, , ! , , , , , , . , .

+1

If you encounter a CORS problem in AngularJS applications when accessing the REST API running on the localhost machine, check the following: add the CORS filter to your server application. In my case, I added the code below in a Spring application

import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

@Component
public class SimpleCORSFilter implements Filter {

private final Logger log = LoggerFactory.getLogger(SimpleCORSFilter.class);

public SimpleCORSFilter() {
    log.info("SimpleCORSFilter init");
}

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

    HttpServletRequest request = (HttpServletRequest) req;
    HttpServletResponse response = (HttpServletResponse) res;

    response.setHeader("Access-Control-Allow-Origin", request.getHeader("Origin"));
    response.setHeader("Access-Control-Allow-Credentials", "true");
    response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
    response.setHeader("Access-Control-Max-Age", "3600");
    response.setHeader("Access-Control-Allow-Headers", "Content-Type, Accept, X-Requested-With, remember-me");

    chain.doFilter(req, res);
}

@Override
public void init(FilterConfig filterConfig) {
}

@Override
public void destroy() {
}

}

In angularjs code, do not specify the URL as http: // localhost : 8080 /../. Instead of localhost, enter your host IP address.

It will work fine

+1
source

A friend of mine. Type only

/DocumentRESTService.svc/GetDocuments
-1
source

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


All Articles