我是angularjs的新手,并尝试使用angularjs client来使用wcf restful服务 . 最初我曾尝试过http.get(url)并得到了CORS问题,我通过将以下代码放入我想要调用的wcf服务方法中来解决 .
WebOperationContext.Current.OutgoingResponse.Headers.Add("Access-Control-Allow-Origin", ""); WebOperationContext.Current.OutgoingResponse.Headers.Add("Access-Control-Allow-Methods", "POST,GET,OPTIONS"); WebOperationContext.Current.OutgoingResponse.Headers.Add("Access-Control-Allow-Headers", "Content-Type, Accept");*
现在当我拨打电话(http.post)的方式与我做的相同时,我得到了回复CORS问题 .
但是当我在发帖时尝试传递JSON对象时,我再次开始遇到CORS问题 .
我的帖子角度代码是:
var requestData = {
RequestUserName: "Abc1",
RequestPass: "123"
};
var req = {
method: 'POST',
url: 'url',
headers: {
'Content-Type': 'application/json; charset=utf-8'
},
data: requestData
};
$http(req).success(function(){console.log("Success");
$scope.userDetails = response.UserNameAuthenticationResult;}).error(function(){console.log("Error");});
我的WCF操作 Contract 如下所示:
[WebInvoke(Method="POST",UriTemplate="/Authenticate"
,RequestFormat=WebMessageFormat.Json
,ResponseFormat=WebMessageFormat.Json
,BodyStyle = WebMessageBodyStyle.Wrapped)]
string UserNameAuthentication(Request request);
和方法实现如下:
public string UserNameAuthentication(Request request)
{
WebOperationContext.Current.OutgoingResponse.Headers.Add("Access-Control-Allow-Origin", "*");
WebOperationContext.Current.OutgoingResponse.Headers.Add("Access-Control-Allow-Methods", "POST,GET,OPTIONS");
WebOperationContext.Current.OutgoingResponse.Headers.Add("Access-Control-Allow-Headers", "Content-Type, Accept");
return "true";
}
我得到的错误如下:
**选项URL(匿名函数)@ angular.js:11442sendReq @ angular.js:11235serverRequest @ angular.js:10945processQueue @ angular.js:15552(匿名函数)@ angular.js:15568 $ eval @ angular.js: 16820 $ digest @ angular.js:16636 $ apply @ angular.js:16928(匿名函数)@ angular.js:24551defaultHandlerWrapper @ angular.js:3398eventHandler @ angular.js:3386 localhost /:1 XMLHttpRequest无法加载http://本地主机:8733 / TestService的/登录/验证 . 对预检请求的响应未通过访问控制检查:请求的资源上不存在“Access-Control-Allow-Origin”标头 . 因此不允许来源'http:// localhost:14703'访问 . 响应具有HTTP状态代码405 .
2 回答
CORS是浏览器和服务器设置之间的交互 .
发布请求和响应标头会很有用 .
我假设您正在与不同域上的API进行交互,例如api.example.com而不是www.example.com . 服务器可以设置Access-Control-Allow-Origins响应头 . 要允许所有来源作为临时措施,请将其设置为“*”而不是空字符串,但很快您应将其设置为您网站的实际来源,例如www.example.com
实际上,您可能不希望它完全打开,因为它可能存在安全风险,有人可能会创建您网站的虚假版本 .
一起避免CORS的简单方法是使用代理服务器 . 这样所有请求都会转到同一个域(包括html和API) . 如果运行节点应用程序,则可以使用node-http-proxy或类似方法 . 如果您有自定义标头或数据,这也可以避免预检请求 . 预检请求是您在实际请求之前在API上看到的OPTIONS请求 .
以下是有关预检行为的更多信息:https://www.soasta.com/blog/options-web-performance-with-single-page-applications/
看起来在服务器端没有启用CORS,因为OPTIONS方法不被理解 .
也许试试这个: