AngularJS $http.get not retrieving the backend data - javascript

i am new to the "Angularjs and Nodejs" combination and i am trying to make a simple crud app. The problem is, when i use $http.get in angular, it doesnt go to the backend.
Here are my codes:
server.js (nodejs)
var connection = util.getDBConnection();
app.use(express.static(__dirname + "/public"));
app.use(bodyParser.json());
//routes = require('./routes/routes')(app, connection);
app.get('/', function(req, res) {
console.log("Backend");
connection.query("SELECT * FROM user_info;", function(err, rows){
if(err){
res.redirect('/error');
console.log("Error in the database: " + err);
}
res.end(JSON.stringify(rows));
console.log("Connected to the Database!");
});
});
angularmodule.js
var app = angular.module('two_way', ['ngRoute']);
app.controller('two_way_control', function($scope, $http){
$scope.message = "Hello from controller";
$http.get('/').success(function(data){
console.log("http get");
console.log(data);
$scope.profile_pictures = data;
});
});
and console.log(data) returns the whole index.html
index.html
<body>
<div id="container" ng-app="two_way" ng-controller="two_way_control">
<div class="row" ng-repeat="data in profile_pictures">
{{message}}
<div class=".col-sm-6 .col-md-5 .col-lg-6">
<h4>User Say's</h4><hr>
<p>
This is a Demo feed. It is developed to demonstrate Two way data binding.
</p>
{{ data.profile_picture }}
<img src="{{data.profile_picture}}">
</div>
</div>
</div>
</body>
But this code returns the mysql data in json format:
app.get('/load', function(req, res) {
console.log("Backend");
connection.query("SELECT * FROM user_info;", function(err, rows){
if(err){
res.redirect('/error');
console.log("Error in the database: " + err);
}
res.end(JSON.stringify(rows));
console.log("Connected to the Database!");
});
});
Please help. Thanks in advance and sorry for the bad english.

For fix the error in the chrome console
"GET http://localhost:8000/%7B%7Bdatas.profile_picture%7D%7D 404 (Not Found)"
i suggest you to use the ngSrc directive, so instead of
<img src="{{datas.profile_picture}}">
use
<img ngSrc="{{datas.profile_picture}}">
As described in the doc
Hope this help

In Express, you need to respond with a request. Use something such as res.send and send data down.
http://expressjs.com/api.html#res.send
Sends the HTTP response.
The body parameter can be a Buffer object, a String, an object, or an
Array. For example:
res.send(new Buffer('whoop'));
res.send({ some: 'json' });
res.send('<p>some html</p>');
res.status(404).send('Sorry, we cannot find that!');
res.status(500).send({ error: 'something blew up' });
This method performs many useful tasks for simple non-streaming responses:
For example, it automatically assigns the Content-Length HTTP response header field (unless previously defined) and provides automatic HEAD and HTTP cache freshness support.
When the parameter is a Buffer object, the method sets the Content-Type response header field to “application/octet-stream”, unless previously defined as shown below:
res.set('Content-Type', 'text/html');
res.send(new Buffer('<p>some html</p>'));
When the parameter is a String, the method sets the Content-Type to “text/html”:
res.send('<p>some html</p>');
When the parameter is an Array or Object, Express responds with the JSON representation:
res.send({ user: 'tobi' });
res.send([1,2,3]);
http://expressjs.com/api.html#res.end
Ends the response process. Inherited from Node’s http.ServerResponse.
Use to quickly end the response without any data. If you need to respond with data, instead use methods such as res.send() and res.json().
res.end();
res.status(404).end();

I got the answer, i just need to initiate the http function
var app = angular.module('two_way', []);
app.controller('two_way_control', function($scope, $http){
$scope.message = "Hello from controller";
$scope.load = function(){
$http.get('/LoadAll').success(function(data){
console.log("http get");
$scope.profile_pictures = data;
});
};
$scope.load();
});
but i still get an error in the chrome console
"GET http://localhost:8000/%7B%7Bdatas.profile_picture%7D%7D 404 (Not Found)"
in <img src="{{datas.profile_picture}}">

Change
<img src="{{datas.profile_picture}}">
to
<img src="{{data.profile_picture}}">

Related

Nodejs wait for socket and then respond to http request

I have a NodeJS code where, basically this is what happens:
HTTP request (app.get) -> Send a request to a low level socket(using net.Socket()) -> Get response from socket -> res.send(response from socket)
This doesn't work because the net.Socket() uses async functions and events (client.on("data", callback)).
I tried something like this:
app.get("/", function(req, res){
client.connect("localhost", 420, function(){
client.write("example data");
});
client.on("data", function(data){
client.destroy();
res.send(data);
});
});
But it doesn't work because it says I am re-sending the headers (the res object won't change since the function is an event, not a sync function).
Any ideas? Or a library for sync socket requests? I have tried the following:
Synket
sync-socket
netlinkwrapper
And they don't work.
Edit: I am trying something like this:
async function sendData(client, res){
client.on('data', function(data){
console.log("Got data!");
res.send(""+data);
res.end();
console.log("Sent data!");
client.destroy();
console.log("Killed connection");
return;
});
}
app.get("/", function(req, res){
var body = req.query;
client.connect(420, "localhost", function(){
client.write("some random data");
console.log("Connected & Data sent!");
sendData(client, res);
});
});
It works the first time I try to access the page, but the second time the app crashes and I get this error:
_http_outgoing.js:489
throw new Error('Can\'t set headers after they are sent.');
^
Error: Can't set headers after they are sent.
client triggles data event multiple times.
`app.get("/", function(req, res){
client.connect("localhost", 420, function(){
client.write("example data");
});
client.pipe(res);
});
});
`
It turns out that, each time a request comes to that endpoint, a new subscription has been registered by calling the client.on('eventName', cb). So, calls starting from the second one will trigger multiples of those registrations and will cause that header error.
So, a workaround for that:
socket.on('event', (packet) => {
socket.removeAllListeners('event')
res.json({ packet });
});
That would do the trick but I'm not sure if it's a bad practice to continuously add/remove the same event.
Edit
Found a better way. once will ensure that registered event only will run once, just as we want:
socket.once('event', (packet) => {
res.json({ packet });
});

Empty return of NodeJS in Angular

My NodeJs application return in this url (http://localhost:3000/api/campaigns) a json response.
But when my Angular application call this url, get a empty response.
I try to change the 200 http code to 404, and I see this change, but always there ara a empty response.
Angular:
var campaigns = function(country) {
var deferred = $q.defer();
$http.get( "http://localhost:3000/api/campaigns" ).then(function(response) {
deferred.resolve(response);
}, function(response) {
deferred.reject(response);
});
return deferred.promise
}
And in my NodeJs code:
exports.findAllCampaigns = function(req, res) {
Campaign
.find({})
.limit(10)
.exec(function(err, campaigns) {
if(err) res.send(500, err.message);
res.status(200).jsonp(campaigns);
});
};
In my browser console, the XHR request is always empty (http 200).
This is just to have a response on this question (i would like that either charlietfl or Carlos Vazquez posted this as response rather than me :) )
BY charlietfl --> Just implement CORS in api
BY Carlos Vázquez --> Thanks! I just enabled the cors middleware with:
var cors = require('cors');
var app = express();
app.use(cors());

Can't get data from $http.post

So basically, I have a form and I cannot fetch data typed into it.(I'm using angular and node.js)
req.body
req.params are both empty
My html form :
<form ng-submit="sendTradelink()">
<md-input-container class="md-accent">
<label>Enter your tradelink</label>
<input ng-model="tradelink">
</md-input-container>
<md-button type="submit" class="md-raised md-accent">Send</md-button>
</form>
Controller :
$scope.sendTradelink = function () {
Auth.send()
.success(function (res) {
$location.path('/');
});
}
Service :
authFactory.send = function (tradelink) {
return $http.post($api.url + 'tradelink', {tradelink: tradelink});
};
Server side file where I want to work with data inserted into form:
api.post('/tradelink', function(req, res){
console.log(req.user.id);
console.log(req.params);
console.log(req.body);
res.json({
success: true,
message: 'tradelink received'
})
});
logs for controlling, empty every time.
As mentioned in comments, Express does not parse the body. POST requests are much more complex that GET ones, so the parser lies in a separate package, body-parser:
npm install --save body-parser
// server.js
api.use(bodyParser.urlencoded({
extended: true
}));
api.post('/tradelink', function(req, res) {
console.log(req.body.tradelink);
});
#Amadan answer is right. You also need to update the controller:
Auth.send($scope.tradelink)

How to return data response using express?

I am trying to run .get on a JSON file I've set up located at /scripts/src/data/*.json when I make the request I set the headers but I'm not sure how I actually return the resulting data or where I can view this request. Can someone offer any help?
JS
server.get('/scripts/src/data/*.json', function(req, res) {
res.setHeader("Content-Type", "application/json");
// return ??
});
You could use static middleware to serve your json files ,
server.use(express.static(__dirname + "/scripts/src/data"))
//other routes
In client side , you just should request GET localhost:port/file.json
Try this:
server.get('/scripts/src/data/*.json', function(req, res) {
res.setHeader("Content-Type", "application/json");
res.status(200);
res.json({
hello: "world"
});
// return ??
});

Correct way to protect URL with JSON web token and node.js/express

I'm currently authorizing users with JSON web tokens using node.js and express with EJS as the view engine.
Using simple middleware in my server.js file:
app.use(function(request, response, next){
var token = request.body.token || request.query.token || request.headers['x-access-token'];
console.log(request.body);
if(token){
jwt.verify(token, app.get('superSecret'), function(err, decoded){
if(err){
response.json({"message": "Failed to authenticate user"});
}
else{
request.decoded = decoded;
next();
}
});
}
else{
return response.status(403).json({"message":"No token was provided"});
}
});
and protected routes below it e.g:
app.post('/userlist', function(request, response) {
response.json({some: json})
});
What I can't understand or figure out is how to protect a GET route such as:
app.get('/userprofile', function(request, response) {
response.render('pages/userprofile');
});
If I make the request by some url directly www.example.com/userprofile access is denied, as there is no token included with the request.
If I make it via ajax:
$.ajax({
type:"GET",
url:"https://www.example.com/userprofile",
headers:{"x-access-token": token },
success: function(result, success){
},
error: function (result, error){
}
});
The response is not rendered but comes back in the result object. I've got my wires crossed somewhere here.
A token needs to be passed in order to be used. If the server doesn't have access to it, the server can't validate it. So, you can pass the token in the path :
app.get('/userprofile/:token',function(request,response){
console.log(request.params.token);
});
In the query string :
app.get('/userprofile',function(request,response){
console.log(request.query.token);
});
Or as a cookie :
var cookieParser = require('cookie-parser');
app.use(cookieParser);
app.get('/userprofile',function(request,response){
console.log(request.cookies.token);
});
http response code should be sent, default is 200 as in your case response.json({"message": "Failed to authenticate user"});
try
response.json(401, {"message": "Failed to authenticate user"});

Categories