1

I have a problem with my AngularJS application. I build a Node.js RESTful API for simple GET and POST functions. If I use a test client to send the http-request, all worked fine and I get my data back. But if I try to use the same request in my angular-js application, I got an error and I don't know why.

here is the code of my node.js app

the www.js:

var app = require('../app');
var http = require('http');

var port = '3000';
app.set('port', port);
var server = http.createServer(app);
server.listen(port);

app.js:

var express = require('express');
var bodyParser = require('body-parser');

var routes = require('./routes/index');
var users = require('./routes/users');

var app = express();

app.use(bodyParser.json());

app.use('/api/v1/', routes);
app.use('/api/v1/users', users);

users.js:

router.get('/', function (req, res, next) {

    db_pool.getConnection(function (err, conn) {
        if (err) {
            conn.release();
            res.json({"code": 100, "status": "Error in connection database"});
            return;
        }

        console.log('connected as id ' + conn.threadId);
        conn.query("select * from Users", function (err, rows) {
            conn.release();
            if (!err) {
                res.setHeader('content-type', 'application/json');
                res.json(rows); // fetch rows
            } else {
                res.json({"code": 404, "status": "No Users available"});
            }
        });

        conn.on('error', function (err) {
            res.json({"code": 100, "status": "Error in connection database"});
            return;
        });
    });

});

And here is my Angular-JS code: app.js:

'use strict';

angular.module('tutorialApp', [])
    .controller('UsersCtrl', function($scope, $http){
        $http.get('http://localhost:3000/api/v1/users').success(function(usersResponse) {
            $scope.users = usersResponse.data;
        }).error(function (response, status, header, config) {
            alert("ouh, an error...");
        });
    });

and the HTML-Site:

<script src="../js/angular.min.js"></script>
<script src="../js/modules/app.js"></script>


<div class="container">
    <input type="text" ng-model="search">

    <p ng-show="search">You searching for: {{search}}</p>

    <table class="table" ng-controller="UsersCtrl">
        <tr ng-repeat="user in users | filter:search">
            <td>{{user.user_id}}</td>
            <td>{{user.first_name}}</td>
            <td>{{user.last_name}}</td>
        </tr>
    </table>
</div>

what do I wrong?

3
  • 1
    Try using $http.get('/api/v1/users') instead of full URL Commented Nov 30, 2015 at 20:12
  • Isn't it a cross-domain error? Commented Nov 30, 2015 at 20:30
  • I started the angular-js app without any server behind (just double-click the html-file from File Browser). If I put an static json-file in the $http.get function, it worked. But without any server, I couldn't use relative URLs, do I? Commented Dec 1, 2015 at 10:31

2 Answers 2

1

Your issue is likely due to the following deprecation:

The $http legacy promise methods success and error have been deprecated. Use the standard then method instead. If $httpProvider.useLegacyPromiseExtensions is set to false then these methods will throw $http/legacy error.

via https://docs.angularjs.org/api/ng/service/$http

Try using more streamlined code with success/failure callbacks and relative urls when it's the same host :

$http.get('/someUrl', config).then(successCallback, errorCallback);

Which for your code would look something like:

$http.get('/someUrl', config).then(
  function(usersResponse) { $scope.users = usersResponse.data;},
  function (res) { alert("ouh, an error..."); }
);

Also, I highly recommend Restangular, I feel it's much easier and efficient than $http alone. It's built on top of $http, just a more contextual and user-friendly setup.

Sign up to request clarification or add additional context in comments.

1 Comment

I wish when people gave a down-vote, they would share the reason in a comment. Is there misinformation here? Did they dislike that I recommended a different module? I believe I still answer the question as OP asked it.
0

Okay, after I use node.js for serving my angular-page and reduce the URL to a relative URL, all works fine. Thanks for your help.

Now my UsersCtrl looks like:

'use strict';

angular.module('tutorialApp', [])
    .controller('UsersCtrl', function($scope, $http){
        $http.get('/api/v1/users').then(function(usersResponse) {
            $scope.users = usersResponse.data;
        })
    });

1 Comment

FYI it's uncouth to answer your own question unless the info was not already provided - what you did above was provided by answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.