Reputation: 19
Hello today I have simple code Nodejs express that work as rest api. It work when i use postman to send request as get method like code below. But i try use it in client. it doesn't work . So can you help find mistake,please?
// simple rest api
router.get('/getuser', function(req, res, next) {
var connection = getcon();
res.setHeader('Content-Type', 'application/json');
connection.query('SELECT username,password from tbuser', function (error, results, fields) {
if (error) throw error;
console.log('Object : ', JSON.stringify(results));
res.send(JSON.stringify(results));
});
connection.end();
});
// client code
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope, $http) {
$http.get("http://localhost:3000/users/getuser")
.then(function(response) {
$scope.myWelcome = response.data;
});
});
</script>
Upvotes: 0
Views: 2224
Reputation: 359
You need to enable Cross-Origin Resource Sharing, a mechanism gives web servers cross-domain access controls, which enable secure cross-domain data transfers. Add this before your router:
app.use(function (req, res, next) {
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');
res.setHeader('Access-Control-Allow-Headers', 'Content-type');
res.setHeader('Access-Control-Allow-Headers', 'X-Signature');
res.setHeader('Access-Control-Allow-Headers', 'X-Key');
next();
}
);
Upvotes: 0
Reputation: 634
It seems like you supply incorrect URL in the client script.
Based on your nodejs code URL must be http://localhost:3000/getuser
UPDATE
You end your connection before you send results. Just move connection.end()
inside your callback
if (error) throw error;
console.log('Object : ', JSON.stringify(results));
res.send(JSON.stringify(results));
connection.end();
});
Upvotes: 1