如何在客户端和服务器端使用jsonp和CORS实现网页上的跨域ajax调用。
例如,在www.mytestsite.com上,要对www.otherdestinationserver.com进行ajax调用,如何使用JSONP或CORS实现?
发布于 2017-04-23 08:02:29
最后,在研究和浏览了所有其他帖子后,我找到了一些解决方案。我正在为这两种方法写答案。
1.只使用JSONP而不使用CORS:如果使用JSONP,总是需要进行服务器端更改以获得带有
callback方法的json响应。此外,要执行的javascript中必须存在callback方法。因此,在下面的示例中,当我们调用目标url时,如果我们得到的响应是myCallBackMethod({ "customerData": { "name": "testName", "age": 26 } }),那么我们必须有一个名称为myCallBackMethod的javascript method。使用jsonp、cookies can also be shared across domains
callback方法是myCallBackMethod。此名称可以是除response jsonp string must match和javascript中的名称之外的任何名称
客户端/ javascript:
function makeTheCall(queryString) {
var destinationUrl = "www.otherdestinationserver.com";
$.ajax({
type: 'GET',
url: destinationUrl + queryString,
dataType: 'jsonp',
jsonpCallback: 'myCallBackMethod',
async: false, // this is by default false, so not need to mention
crossDomain: true // tell the browser to allow cross domain calls.
// success: successResopnse, jsonpCallback will call the successCallback
// error: failureFunction jsonp does not support errorCallback. So cannot use this
});
}
window.myCallBackMethod = function(data) {
successResponse(data);
}
successResponse = function(data) {
//functionality goes here;
}
// the json response from the server when calling the url must be in the below format only.
myCallBackMethod({ "customerData": { "name": "testName", "age": 26 } })
2.只使用CORS,不使用JSONP,也不使用URL重写:如果使用CORS,总是有一个
need to make changes on server and client/javascript。在这种方法中,no need to get any callback方法作为json响应的一部分。响应must be a pure json。但是,请在目标服务器上进行适当的代码更改,以允许请求通过。所以需要在response对象中设置header。
客户端/ javascript:
function makeTheCall(queryString) {
var destinationUrl = "www.otherdestinationserver.com";
$.ajax({
type: 'GET',
url: destinationUrl + queryString,
dataType: 'json', // use json only, not jsonp
crossDomain: true, // tell browser to allow cross domain.
success: successResopnse,
error: failureFunction
});
}
successResponse = function(data) {
//functionality goes here;
}
failureFunction = function(data) {
//functionality goes here;
}
在服务器上,添加下面的标头。
httpServletResponse.setHeader("Access-Control-Allow-Origin", "*"); // Here need to give the origin url (the url in the address bar of the page which is making request). Using * means allow any value客户端/javascript上的:
xhrFields: {
'withCredentials': true // tell the client to send the cookies if any for the requested domain
}服务器上的:
httpServletResponse.setHeader("Access-Control-Allow-Credentials", "true");Access-Control-Allow-Origin,则对报头Access-Control-Allow-Origin的值有限制。它应该是never be * if we want to use Access-Control-Allow-Credentials header。因此,请提供确切的域名。服务器上的更新:
httpServletResponse.setHeader("Access-Control-Allow-Origin", "www.mytestsite.com"); // Give the origin url (the url in the address bar of the page which is making request).最终客户端/ javascript:(仅CORS方法)
function makeTheCall(queryString) {
var destinationUrl = www.otherdestinationserver.com;
$.ajax({
type: 'GET',
url: destinationUrl + queryString,
dataType: 'json', // use json only, not jsonp
crossDomain: true, // tell browser to allow cross domain
xhrFields: {
'withCredentials': true // tell the client to send the cookies if any for the requested domain
},
success: successResopnse,
error: failureFunction
});
}
successResponse = function(data) {
//functionality goes here;
}
failureFunction = function(data) {
//functionality goes here;
}
最终服务器代码:(仅CORS方法)
httpServletResponse.setHeader("Access-Control-Allow-Credentials", "true");
httpServletResponse.setHeader("Access-Control-Allow-Origin", "www.mytestsite.com");3.仅与CORS配合使用URL重写过滤器设置响应头:
如果应用程序使用url重写过滤器(大多数web应用程序都是这样),这将提供更容易的实现。不是遵循上面方法2中的最终服务器代码:(仅CORS方法),而是遵循下面的url来更改xml ( url重写过滤器)。
为了快速参考,下面粘贴了相同的代码。
<rule enabled="true" match-type="regex">
<name>Enabling CORS Headers</name>
<from>^/path/someMorePath.*$</from>
<condition name="origin" operator="equal">([a-z]+)</condition>
<set type="response-header" name="Access-Control-Allow-Origin">%1</set>
<set type="response-header" name="Access-Control-Allow-Credentials">true</set>
发布于 2018-09-29 03:23:28
如果你不能控制服务器端,你可以像我一样在
仅限客户端。
如果你可以控制服务器端,你可以使用服务器端的解决方案。我不是在这里讨论它。
仅在客户端,解决方法是
使用dataType:'jsonp',
async function get_ajax_data(){
var _reprojected_lat_lng = await $.ajax({
type: 'GET',
dataType: 'jsonp',
data: {},
url: _reprojection_url,
error: function (jqXHR, textStatus, errorThrown) {
console.log(jqXHR)
},
success: function (data) {
console.log(data);
// note: data is already json type, you just specify dataType: jsonp
return data;
}
});
} // function https://stackoverflow.com/questions/43521856
复制相似问题