angularjs 资源 post 和 body

angularjs resource post with body

我是 angularjs 的新手,我正在尝试 post 使用 body 存在的资源 api 当我在 postman 上发送带有 body 的 post 时,它工作正常,请登录并取回令牌

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.

当我 debig api 当我到达 api 时,viewModel 为空 为什么它为空 他不明白我的 body

我尝试用参数替换 body 但相同

感谢帮手

您正在请求从一个域到另一个域,例如从 www.xyz.com 到 www.abc.com。在您的情况下,您请求从 Origin 'localhost:53647'.

'localhost:9303/v1/token'

出于调试目的,您可以为 google chrome 和其他浏览器使用 Allow-Control-Allow-Origin 插件,否则您需要配置并允许 localhost:9303/ 接受请求来自其他域。

好吧,我想分享我对这个问题的解决方案 经过大量研究后,我发现当您尝试 post 访问网络 api 时,您必须在同一个域中,这是典型的跨域问题

首先你需要在 package menage console 上安装

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();

并且需要将此行添加到网络上的 post 方法中 api

[EnableCors(origins: "*", headers: "*", methods: "*")]

希望对某人有所帮助 此致