Ajax - 'Origin localhost is not allowed by Access-Control-Allow-Origin'

后端 未结 1 425
北海茫月
北海茫月 2020-12-07 03:08

I\'m relatively new to Ajax and was just tasked with this cross-domain call. We have a text box on our web page that a user will use to preform a search of company names. By

相关标签:
1条回答
  • 2020-12-07 03:29

    This error is due to the restriction enforced in cross-domain resource sharing. This has been implemented as a part of security feature to restrict the clients(domain) of a resource via cross domain calls. When you send a request to the webservice or api or similar, it adds Origin header in the request for the server or destination (here your api) to validate if the request is coming from an authorized source or not. Ideally the api/server should look for the Origin in the Request header it received and probably validate against the set of origins(domains) which it is permitted to serve the resources to. If it is coming from a permitted domain it will add the same domain in the response header as "Access-Control-Allow-Origin" value. wildcard is also permitted for this, but the issue is that with wild card permission any one can make a request and get it served (with some restrictions like an api is authenticated via windows auth or cookies where you need to send the withCredentials value * is not allowed). it is not a good practice to use wildcard origin the response header which makes it open to everyone.

    These are some ways to set the response header with the values:-

    Access-Control-Allow-Origin: *
    Access-Control-Allow-Origin: http://yourdomain.com
    

    you can even add multiple Access-Control-Allow-Origin headers in the same response (I believe works in most browsers)

    Access-Control-Allow-Origin: http://yourdomain1.com
    Access-Control-Allow-Origin: http://yourdomain2.com
    Access-Control-Allow-Origin: http://yourdomain3.com
    

    On the server side (c# syntax) you would do this:-

    var sourceDomain = Request.Headers["Origin"]; //This gives the origin domain for the request
         Response.AppendHeader("Access-Control-Allow-Origin", sourceDomain ); //Set the response header with the origin value after validation (if any) .Depending on the type of application you are using syntax may vary.
    

    Hope this helps!!!

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