zl程序教程

您现在的位置是:首页 >  其他

当前栏目

No ‘Access-Control-Allow-Origin’ header is present on the requested resource详解编程语言

On编程语言 详解 &# The is No access
2023-06-13 09:20:31 时间

No Access-Control-Allow-Origin header is present on the requested resource. Origin http://test.123.com:808 is therefore not allowed access.

出现这种问题是时因为浏览器出现了跨域的请求。在http://test.123.com:808网站中请求了其他域中的页面。

有两种方法进行修改。

1使用jsonp的方法修改

  使用jsonp的方法其实就是类似于请求js脚本的方法,js脚本的是允许跨域的。

  jquery的写法如下:

 $.ajax({ 

 type: "post", 

 dataType: "jsonp", 

 url: "http://test.123.456.cn/wxkq/Portlets/ToDoInfo.ashx?OperationType=todocount", 

 data: data, 

 error:function (or) { 

 success: function (or) { 

 });

核心的是dataType修改为jsonp,但实际过程和一般的json差别特别大。

因此后台也需要进行一定的修改

 public void ProcessRequest(HttpContext context) 

 context.Response.ContentType = "application/json"; 

 OperationResults or = new OperationResults(); 

 string uid = GetFormString("userid"); 

 string Groupid = GetFormString("Groupid"); 

 string Callback = GetFormString("Callback"); 

 if (string.IsNullOrEmpty(uid) || string.IsNullOrEmpty(Groupid)) 

 else 

 int userid = int.Parse(GetFormString("userid")); 

 UserSession se = initUserSession(userid, Groupid); 

 ToDoCountAction(or, se); 

 string returnStr = NewtonsoftConver.ObjToJsonString(or); 

 context.Response.Write(Callback + "(" + returnStr + ")"); 

 }

核心是会添加一个查询字符串Callback,然后返回Callback( 返回结果 ),到了前台其实就是一个js脚本,就相当于在前台调用了一个js方法

Callback( 返回结果 ),只不过这个js函数的传入参数是后台生成的。

2后台方法允许跨域

 public void ProcessRequest(HttpContext context) 

 context.Response.AddHeader("Access-Control-Allow-Origin", "http://test.123.com:808"); 

 context.Response.ContentType = "application/json"; 

 string Callback = GetFormString("Callback"); 

 string returnStr = NewtonsoftConver.ObjToJsonString(or); 

 context.Response.Write(Callback + "(" + returnStr + ")"); 

 }

核心

context.Response.AddHeader( Access-Control-Allow-Origin , http://test.123.com:808 );

允许任意网站访问

ntext.Response.AddHeader( Access-Control-Allow-Origin , * );

对于HTML页面可以添加,但没有测试

 meta http-equiv="Access-Control-Allow-Origin" content="*" 

原创文章,作者:ItWorker,如若转载,请注明出处:https://blog.ytso.com/11223.html

cjava