Angular2 to REST WebApi CORS issue

后端 未结 10 1960
太阳男子
太阳男子 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: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.

提交回复
热议问题