Angular2 to REST WebApi CORS issue

后端 未结 10 1931
太阳男子
太阳男子 2020-12-15 06:50

I\'m using an angular2 front end and WebApi backend. The webapi is CORS enabled

var cors = new EnableCorsAttribute(\"*\", \"*\", \"*\");
GlobalConfiguration.         


        
相关标签:
10条回答
  • 2020-12-15 07:10

    Your error message tells that there is no Access-Control-Allow-Origin in the response of your call. It's something necessary to enable CORS for this request. It's not something related to Angular2.

    This is triggered on the client side by the adding of the Origin header in the request. Do you have this header in your request? Do you use preflighted requests in your other applications. As a reminder:

    • Simple requests. This use case applies if we use HTTP GET, HEAD and POST methods. In the case of POST methods, only content types with the following values are supported: text/plain, application/x-www-form-urlencoded and multipart/form-data.
    • Preflighted requests. When the "simple requests" use case doesn't apply, a first request (with the HTTP OPTIONS method) is made to check what can be done in the context of cross-domain requests.

    Perhaps OPTIONS requests aren't correctly handled on the server side (don't return correct headers, ...).

    What would be interested is to tell us on which requests the error occurs: the OPTIONS one or the target request. You can have a look at the Network tab in DevTools...

    See these links for more details about how CORS works:

    • http://restlet.com/blog/2015/12/15/understanding-and-using-cors/
    • http://www.asp.net/web-api/overview/security/enabling-cross-origin-requests-in-web-api#enable-cors

    Hope it helps you, Thierry

    0 讨论(0)
  • 2020-12-15 07:12

    I had the same issue in my Angular2 application. The problem, as already stated, is that before every request made by the client a preflight request is sent to the server.

    This kind of request have a type OPTIONS, and it's duty of the server to send back a preflight response with status 200 and headers set for accepting requests from that client.

    This is my solution (with express):

    // Domain you wish to allow
    res.setHeader('Access-Control-Allow-Origin', 'http://localhost:3000');
    
    // Request methods you wish to allow
    res.setHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE');
    
    // Request headers you wish to allow
    res.setHeader('Access-Control-Allow-Headers', 'YOUR-CUSTOM-HEADERS-HERE');
    
    // Set to true if you need the website to include cookies in  requests
    res.setHeader('Access-Control-Allow-Credentials', true);
    
    // Check if preflight request
    if (req.method === 'OPTIONS') {
        res.status(200);
        res.end();
    }
    else {
        // Pass to next layer of middleware
        next();
    }
    

    As you can see, i set the headers and then fetch if the request type is OPTIONS. In that case i send back a status 200 and end the response.

    In this way, the client will be authorized and you will be also able to set your custom headers in all the requests.

    0 讨论(0)
  • 2020-12-15 07:16

    I had also hard time with cors and angular 6.

    when a request to the server is not a basic request, there is preflight request asking your server if it can answer to your request.

    the server respond to that request should have those headers:

    Access-Control-Allow-Origin // should be your domain

    Access-Control-Allow-Headers // should be Accept, Origin, any other headers you might have.

    Access-Control-Allow-Method // any methods you use

    those are the " * ", " * ", " * " you added as Cors Attributes to accept all but that only worked for me in dev mode when both client and server were on same machine. after i moved to production with IIS server those values did not worked anymore especially because of the headers.

    so it really easy to fix and it also working for IOS instead * * * i added this to each controller:

    [EnableCors(origins: "enter your domain here", headers: "authorization, Origin, Accept, X-Requested-With, Content-Type, Access-Control-Request-Method, Access-Control-Request-Headers", methods: "GET,POST", PreflightMaxAge = 600 // optional, SupportsCredentials = true // optional)]
    

    you can read more in the article that helped me understand what i needed to do: https://msdn.microsoft.com/en-us/magazine/dn532203.aspx

    Hope it helps, Tomer.

    0 讨论(0)
  • 2020-12-15 07:18

    I know the question is not asking for PHP code. I got here because of this whole preflight thing and Angular2. When I looked at Matteo's answer, then I realized why the request to my server is coming back with 401. This because in the preflight browser does not send the Authorization token and therefore the server comes back with 401 and the browser thinks CORS is not allowed. Please be aware the code below should only be used in development server unless you know what you're doing.

    In PHP you can do this:

    if (strtolower($_SERVER['REQUEST_METHOD']) === 'options') {
             header('Access-Control-Allow-Origin: ' . $_SERVER['HTTP_ORIGIN']);
             header('Access-Control-Allow-Methods: POST, GET, OPTIONS');
             header('Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Range, Content-Disposition, Content-Type, Authorization');
             header('Access-Control-Allow-Credentials: true');
             echo 'Allowed';
             exit;
    }
    

    OR Nginx

    if ($request_method = 'OPTIONS') {
            add_header 'Access-Control-Allow-Origin' '*';
            add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
            #
            # Custom headers and headers various browsers *should* be OK with but aren't
            #
            add_header 'Access-Control-Allow-Headers' 'DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type';
            #
            # Tell client that this pre-flight info is valid for 20 days
            #
            add_header 'Access-Control-Max-Age' 1728000;
            add_header 'Content-Type' 'text/plain charset=UTF-8';
            add_header 'Content-Length' 0;
            return 204;
         }
    

    Remember whatever other headers you're sending to the server you must be added to Access-Control-Allow-Headers list.

    0 讨论(0)
提交回复
热议问题