使用AngularJS向我的API请求时出错

时间:2015-11-27 19:15:15

标签: angularjs rest symfony

我有一个关于请求我自己的API的问题......问题是当我在localhost中请愿时一切正常,但当我尝试在我的生产环境中执行请求时,我总是得到403 Forbidden ..

我认为是标题但我不知道出了什么问题。

我的Api是在带有FOS RestBundle的Symfony 2中开发的

提前致谢! :)

EDITED!

以下是API登录的AngularJS代码

// Main Controller
    .controller("LoginController", ["$scope", "$http", "CONFIG", function ($scope, $http, CONFIG) {
        // Login access
        $scope.login = function () {
            $http.post(CONFIG.APIURL + '/access/', {
                email: $scope.user.email,
                passwd: $scope.user.passwd
            }).then(function successCallback(response) {
                console.log(response.data);
                $scope.logged = 'Logged In!';
                //redirect to customers
            }, function errorCallback(err) {
                //show error
                console.log(err.data);
                alert('Email or Password incorrect...');
            });

        };

restbundle的API config.yml:

fos_rest:
    format_listener:
          rules:
              - { path: ^/api/, priorities: [ json ], fallback_format: ~, prefer_extension: true }
              - { path: ^/, priorities: [ 'html', '*/*'], fallback_format: ~, prefer_extension: true }
    routing_loader:
        default_format: json
    param_fetcher_listener: true
    view:
        view_response_listener: 'force'
        formats:
            json: true
        templating_formats:
            html: true

控制器:

/**
 * @return array
 * @Rest\Post("/access/")
 * @Rest\View
 */
public function loginApiAction(Request $request)
{
    $session = $request->getSession();

    $email = $request->get('email');
    $passwd = $request->get('passwd');

    $user = $this->getDoctrine()->getRepository('OurentecBundle:User')->findOneBy(array(
        'email' => $email,
        'passwd' => Utils::getHash('sha1', $passwd, HASH_KEY)
    ));

    if ($user) {
        $session->set('auth', true);
        $session->set('user_id', $user->getId());
        $session->set('username', $user->getUsername());
        $session->set('email', $user->getEmail());

        $response = array('status' => 200, 'message' => 'Login OK');
        return new JsonResponse($response, 200);
    }

    $response = array('status' => 401, 'message' => 'Email or password incorrect');
    return new JsonResponse($response, 401);
}

编辑2: 好吧,我尝试过Nelmio CORS,但仍然没有工作..

Nelmio config:

nelmio_cors:
    defaults:
        allow_credentials: false
        allow_origin: []
        allow_headers: []
        allow_methods: []
        expose_headers: []
        max_age: 0
        hosts: []
        origin_regex: false
    paths:
        '^/api/v1/':
            allow_origin: ['*']
            allow_headers: ['Origin', 'X-Requested-With', 'Content-Type', 'Accept']
            allow_methods: ['POST', 'GET']
            max_age: 3600

请求结果:

MacBook-Pro-de-Juan:Ourentec wilde$ http http://localhost/Ourentec/web/app_dev.php/api/v1/customers/11
HTTP/1.1 403 Forbidden
Cache-Control: no-cache
Connection: Keep-Alive
Content-Length: 36
Content-Type: application/json
Date: Sat, 28 Nov 2015 18:25:34 GMT
Keep-Alive: timeout=5, max=100
Server: Apache/2.2.29 (Unix) mod_fastcgi/2.4.6 mod_wsgi/3.4 Python/2.7.8 PHP/5.6.2 mod_ssl/2.2.29 OpenSSL/0.9.8zg DAV/2 mod_perl/2.0.8 Perl/v5.20.0
Set-Cookie: PHPSESSID=595d96a9f15ed67fc18a7a5dd3c75992; path=/
X-Debug-Token: 5e025e
X-Debug-Token-Link: /Ourentec/web/app_dev.php/_profiler/5e025e
X-Powered-By: PHP/5.6.2

{
    "message": "Forbidden", 
    "status": 403
}

编辑3: 我使用jQuery“$.param()”解决了登录问题,以发送数据并更改标题配置“'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'

// Login access
        $scope.login = function () {
            var req = {
                method: 'POST',
                url: CONFIG.APIPROD + '/access/',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
                },
                data: $.param({
                    email: $scope.user.email,
                    passwd: $scope.user.passwd
                })
            };
            $http(req).then(function successCallback(response) {
                console.log(response.data);
                $scope.logged = 'Logged In!';
                //redirect to customers
            }, function errorCallback(err) {
                //show error
                console.log(err.data);
                alert('Email or Password incorrect...');
            });

0 个答案:

没有答案