Have two Visual Studio's running on same computer with following URLs:
http://localhost:47503 (web api, #1)
http://localhost:12345 (client that calls above web api, #2)
Client (#2) hard codes Site #1's <script src="http://localhost:47503/file.js"></script>
. Inside the file.js is a single function:
function GetData() {
$.ajax({
url: 'http://localhost:47503/api/autos',
type: 'GET',
dataType: 'json',
data: { "a": '_1', "b": 'TEST', "c": "val c" },
success: function (result) {
alert("success");
}
});
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost:47503/api/autos?a=_1&b=TEST&c=value+c. (Reason: CORS header 'Access-Control-Allow-Origin' missing).
Thought that since script was loaded from Client #1, that it could be invoked from Client #2 hence bypassing the same origin policy in a way? Script from Client #1 calls back to Client #1. JSONP and CORS are known solutions to problem but want to know if above is possible.
答案 0 :(得分:1)
Thought that since script was loaded from Client #1, that it could be invoked from Client #2 hence bypassing the same origin policy in a way?
No, this is not possible. The origin is always that of the document, not the individual script tags. This is how you are able to load libraries like jQuery from a CDN, but make AJAX requests to your own server.
On a side note, even if the origin were determined by the script making the call (which it never is), your code still wouldn't work, since it would actually be jQuery making the AJAX call.
答案 1 :(得分:0)
阻止跨源请求
您的服务器#1可以通过向其HTTP响应添加标头“Access-Control-Allow-Origin”,明确告知Web浏览器它实际上接受来自其他域的请求。