我对angularjs很陌生,我试图用body来做文章,以便在使用body的情况下存在api,当我在邮递员上发送带有body的帖子时,它的工作原理很好,可以登录并获取令牌。
这个api工作得很好,我如何在angularjs上做到这一点呢?
这是我的代码,这是api
[Route("v1/token")]
[HttpPost]
public IHttpActionResult Post(LoginViewModel viewModel)
{}我的资源工厂
app.factory('getToken', function ($resource, $q) {
return function (email, password) {
console.log(email);
console.log(password);
return $resource('http://localhost:9303/v1/token', {}, {
login: {
method: 'POST',
headers: {
'Content-Type': 'application/jsonp;'
},
body: {
Email: email,
Password: password
}
}
});
}
});这是我的登录功能
loginService.login = function (username, password) {
var deferred = $q.defer();
if (username === 'erez' && password === 'pass') {
var src = getToken('email','password').login(function (result) {
console.log(result);
});
console.log(src);
deferred.resolve(src);
}
else {
deferred.reject({ message: 'Unauthorized user' });
}
return deferred.promise;
}我明白那个错误
POST http://localhost:9303/v1/token (anonymous function) @ angular.js:11442r @ angular.js:11235g @ angular.js:10945(anonymous function) @ angular.js:15552m.$eval @ angular.js:16820m.$digest @ angular.js:16636m.$apply @ angular.js:16928(anonymous function) @ angular.js:24551n.event.dispatch @ jquery-2.2.0.min.js:3r.handle @ jquery-2.2.0.min.js:3
(index):1 XMLHttpRequest cannot load http://localhost:9303/v1/token. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:53647' is therefore not allowed access. The response had HTTP status code 500.当我展开api时,当我到达api时,viewModel是空的,为什么它为空,他没有得到我的身体
我试过用平面语代替身体,但也一样。
谢谢你的帮助
发布于 2016-02-17 10:38:48
您正在请求从一个域到另一个域,例如从www.xyz.com到www.abc.com。在您的示例中,您请求“localhost:9303/v1/token”,并从原产地请求“localhost:53647”。
为了调试的目的,您可以使用允许-控制-允许-源插件的谷歌铬和其他浏览器,否则你需要配置和允许本地主机:9303/接受来自其他领域的请求。
发布于 2016-02-17 15:44:02
嗯,我想分享我对这个问题的解决方案,经过大量的研究,我想当你试图发布到web时,你必须在同一个领域,它是典型的跨域问题。
首先,您需要安装在包菜单控制台上。
Install-Package Microsoft.AspNet.WebApi.Cors如果你有你的web.config应该删除
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="*" />
<add name="Access-Control-Allow-Methods" value="GET, POST, OPTIONS, PUT, DELETE" />
</customHeaders>
</httpProtocol并将其添加到WebApiconfig上
config.EnableCors();,并需要将这一行添加到web api上的post方法中。
[EnableCors(origins: "*", headers: "*", methods: "*")]希望它能帮助别人问候
https://stackoverflow.com/questions/35453978
复制相似问题