Cross Domain AJAX Request

Sometimes you have noticed that the browser refuses access to remote resources which you have requested. Do you know the reason behind it?
The reason behind this is that you try to request a cross domain request from JQuery, the request could be any external file, library or AJAX call.
Because of this request for external resource is not complete and you are not able to fetch data. This could be due to Cross-Origin Resource Sharing (CORS) policy.

Cross-Origin Resource Sharing (CORS)

Generally there is a rule that how a webpage can access an external resource for eg fonts, stylesheet, jquery library, AJAX requests. Under same-origin policy, a web browser do not allow access of a resource which is different from current origin, difference could be port, hostname etc.

This limitation can be resolve by Cross-Origin Resource Sharing (CORS). CORS defines a process where a web browser and web server communicate and determine whether to allow a web page to access a resource which is from different origin.

When you make a cross-origin request the browser sends origin header with a value which contains domain name. You can add a origin header in web.config like this.
This will allow all domain for cross-origin request.

<add name="Access-Control-Allow-Origin" value="*" />

Below line will allow cross-origin requests only from a domain called sharepointcafe.net

<add name="Access-Control-Allow-Origin" value="www.sharepointcafe.net" />

Some times you may noticed below error message in console of browser:
Error - Request header field Content-Type is not allowed by Access-Control-Allow-Headers in preflight response. This error is because in origin header domain name is not allowed for which you are accessing a resource.

Comments

Popular

C# 6.0 New Features

SharePoint Interview Questions and Answers

Calling ASP.Net WebMethod using jQuery AJAX

What is Cloud Computing - A guide for beginners