Nyoa
Nyoa

Reputation: 195

http queries not going through in nodejs/angularjs environment

I'm making a website that uses angularjs combined with nodejs and mongoDB to handle logins and other backend stuff. I've created the API with nodejs and it can be successfully tested by going to localhost:8080/api or by sending HTTP-GET by Postman. However, when I try to make a HTTP-GET using my angularjs code the request fails and returns an empty object.

Object { data: null, status: -1, headers: bd/<(d), config: Object, statusText: "" }

Here is a picture of my browser console when I'm making the request:

enter image description here

I just can't understand why the API works fine through the browser and Postman, but fails when I try to create requests in the code.

---------------------------------SOLUTION---------------------------------

I had to add a line of code in to the response changing this:

router.get('/', function(req, res) {
    res.json({ message: 'hooray! welcome to our api!' });   
});

to this:

router.get('/', function(req, res) {
    res.set('Access-Control-Allow-Origin', '*');    
    res.json({ message: 'hooray! welcome to our api!' });   
});

----------------------------------SOLUTION------------------------------------

Here is my angularjs code

var mainApp = angular.module('mainApp', ['ngRoute']);

mainApp.config(['$routeProvider',
  function($routeProvider) {
    $routeProvider.
      when('/frontpage', {
        templateUrl: 'public/views/frontpage.html',
        controller: 'frontpageController',
        activetab: 'frontpage'
    }).
      when('/login', {
        templateUrl: 'public/views/login.html',
        controller: 'loginController',
        activetab: 'login'
      }).
      otherwise({
        redirectTo: '/frontpage'
      });
}]);

mainApp.controller('mainController', function($scope, $route){
    $scope.$route=$route;
});

mainApp.controller('frontpageController', function($scope){
    $scope.test="frontpage";
});

mainApp.controller('loginController', function($scope, $http){
    $scope.rememberMe = false;
    $scope.submit = function(user){     
    $http({
        method: 'GET',
        url: 'http://localhost:8080/api'
        }).then(function successCallback(response) {
            console.log(response);
        }, function errorCallback(response) {
            console.log('dindu work');
            console.log(response);
        });
    };
});

And here is my nodejs server code

// server.js

// BASE SETUP
// =============================================================================

// call the packages we need
var express    = require('express');        // call express
var app        = express();                 // define our app using express
var bodyParser = require('body-parser');
var mongoose = require('mongoose')

// configure app to use bodyParser()
// this will let us get the data from a POST
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());

var port = process.env.PORT || 8080;        // set our port

mongoose.connect('mongodb://localhost/saunaguard')

var db = mongoose.connection;

db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function(){
    console.log('succes')
});

// ROUTES FOR OUR API
// =============================================================================
var router = express.Router();              // get an instance of the express Router

// test route to make sure everything is working (accessed at GET http://localhost:8080/api)
router.get('/', function(req, res) {
    res.json({ message: 'hooray! welcome to our api!' });   
});

// more routes for our API will happen here

// REGISTER OUR ROUTES -------------------------------
// all of our routes will be prefixed with /api
app.use('/api', router);

// START THE SERVER
// =============================================================================
app.listen(port);
console.log('API open in port ' + port);

Upvotes: 0

Views: 53

Answers (1)

G&#244;T&#244;
G&#244;T&#244;

Reputation: 8053

If your web app and your nodejs backend are on different URLs, try this:

res.set('Access-Control-Allow-Origin', '*');

Upvotes: 1

Related Questions