Ramachandran A
Ramachandran A

Reputation: 107

Angularjs I can't Get response data from HTTP localhost call

I want to get response data from REST api. My Localhost URL :

http://localhost:3000/welcome

My AngularJs Code :

<!DOCTYPE html>
<html>
 <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<body>
<div ng-app="myApp" ng-controller="myCtrl"> 
<h1>{{welcome}}</h1>
</div>

<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope, $http) {
  $http.get("http://localhost:3000/welcome")
    .then(function(response) {
       $scope.welcome = response.data;
  });
});
</script>

</body>
</html>

The response data not showing in h1 tag. I have tested this APi in postman working fine.

This is my Nodejs Server code :

var express = require('express');
var app = express();

app.get('/welcome', function(req,res) {
    res.send("Welcome to Nodejs");

});

app.use(function (req, res, next) {

     // Website you wish to allow to connect
     res.setHeader('Access-Control-Allow-Origin', '*');

     // Request methods you wish to allow
     res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');

     // Request headers you wish to allow
     res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type');

     // Set to true if you need the website to include cookies in the requests sent
     // to the API (e.g. in case you use sessions)
     res.setHeader('Access-Control-Allow-Credentials', true);

     // Pass to next layer of middleware
     next();
 }); 

app.listen(3000, "localhost");

Please help me.. Thank you..

Upvotes: 0

Views: 1912

Answers (1)

Sachila Ranawaka
Sachila Ranawaka

Reputation: 41387

I think this may occur due to the CORS. Otherwise, your code seems to be fine. add the following Access-Control-Allow-Origin headers in your Express server and try it.

app.use(function (req, res, next) {

    // Website you wish to allow to connect
    res.setHeader('Access-Control-Allow-Origin', '*');

    // Request methods you wish to allow
    res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');

    // Request headers you wish to allow
    res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type');

    // Set to true if you need the website to include cookies in the requests sent
    // to the API (e.g. in case you use sessions)
    res.setHeader('Access-Control-Allow-Credentials', true);

    // Pass to next layer of middleware
    next();
});  

Upvotes: 1

Related Questions