AngularJS and Node.js Express - $http.get Success Block Not Being Called - javascript

I'm very new to AngualarJS and Node.js, and I have a problem with my $http.get method's success callback block not being executed. When the request fails, my error callback block works, but when it succeeds, nothing happens.
This is what I have in my server.js:
var express = require('express');
var app = express();
// This is for testing GET connection with server
app.get('/test', function (req, res) {
console.log("Got a GET request from my angular app");
res.send('Hello ANGULAR');
})
var server = app.listen(8081, function () {
var host = server.address().address
var port = server.address().port
console.log("Example app listening at http://%s:%s", host, port)
})
This is what I have in my app.js:
$http.get("http://localhost:8081/test")
.success (function (response) {
alert("GOT A RESPONSE");
})
.error (function() {
alert("SERVER GET TEST FAILED THO");
});
Does anyone know what I'm doing wrong?

Your server's app.get block is missing a response sending :
Try adding :
res.sendStatus(200);
or res.status(XXX).send(*object/string*);
at the end.
Here's the documentation : http://expressjs.com/en/4x/api.html#res

The angular and node.js code look fine. But there could be any number of problems between network, configuration, etc.
The best way to figure this out is to use Chrome Dev tools network panel. Click "Inspect" on your page or Command-ALT-i (Mac).
Click the "network" panel tab to see your request and the response received.

try this :
$http.get('http://localhost:8081/test').then(
function successCallback(response) {
console.log("ok")
},
function errorCallback(response) {
console.log("error") ;
}
);
According to the official documentation, don't use success :
Deprecation Notice
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.

Related

How to avoid node-express from being blocked by fetch call

I have simulated a time consuming asynchronous operation on the node-express route using setInterval. while the setInterval was waiting, node-express didn't respond to another client's request.
what can be done to prevent blocking of the route?
This is the simulation I have used:
I opened two clients and tried to send requests from both of the clients at the same time. the test was done on localhost.
I have tested it again and again, and the second client gets the responses from the server only after all ten of the first client request were responded.
Client:
<button onclick='getManyData()'>Get Data </button>
<script>
function getManyData(){
for(let i=0; i<10;i++){
getData()
}
}
function getData(){
fetch('/api/req1')
.then(res=>res.json())
.then(data=>{
console.log(data)
})
}
</script>
Server:
const express = require('express');
const app = express();
app.use(express.static('public'))
app.get('/api/req1', (req, res) => {
setTimeout(()=>{
res.send({ ok: true })
},500)
})
app.listen(3000, () => { console.log('listen on port 3000') })
This is how it looks on the network:
Update:
I have found that this phenomenon happens only on chrome, but not on firefox (in Firefox, all the requests are answered after approximately 500ms). Any suggestions on why this happens?

Need help to create the server.js to work around the CORS issue

So, I need to hit an API and render the response in a html element. I have my app.js doing this:
let url = 'http://localhost:80/db/abc/query/';
class abc extends Component {
state {userinput:""}
getResponse = () => {
axios.get(url+this.state.userinput, {
headers: {
'Content-Type': 'application/json'
}
})
.then(response => {
this.setState({results: response.data})
});
}
render () { //ignore the render for now
return ()
}
}
export default abc;
But since I was getting the CORS error, I created a server.js & started the proxy using # node server.js command. But for some reason I keep getting Error 500 back from the API.
Server.js
var express = require('express')
var cors = require('cors')
var app = express()
app.use(cors())
app.use('/', function(req, res) {
var url = 'https://' +
req.get('url').replace('localhost:80', 'my-real-host-fqdn:8122') +
req.url
req.pipe(request({ qs:req.query, uri: url })).pipe(res);
})
app.listen(80, function () {
console.log('CORS-enabled web server listening on port 80')
})
I call my getResponse() on a button click, which is working but not included in the excerpt above.
Error Messages:
GET http://localhost/db/abc/query/<userinput> 500 (Internal Server Error)
createError.js:17 Uncaught (in promise) Error: Request failed with status code 500
Errors with proxy server:
CORS-enabled web server listening on port 80
TypeError: Cannot read property 'replace' of undefined
OR
CORS-enabled web server listening on port 80
ReferenceError: request is not defined
I am not very familiar with the server.js file and using express. How does this work, and have I made any mistakes here?
So what did the trick for me was removing this line from my server.js:
req.pipe(request({ qs:req.query, uri: url })).pipe(res);
Posting this here so it helps someone with a similar issue.
Thanks for trying to help guys!!
to get host, use req.get('host'). Seems like req.get('url') is the issue.
app.get('/one/two', function (req, res) {
var url = req.url;
}
How to get the full url in Express?

Send a response to Angular.js in Node.js

Im using Angular with Node and would to send a response to the client-side controller from a GET request.
The line of code Im using to send the response seems not to be working when I use native Node as opposed to Express.js
Here is my angular controller:
app.controller('testCtrl', function($scope, $http) {
$http.get('/test').then(function(response){
$scope = response.data;
});
});
This is routed to essentially the following server script:
http.createServer(function onRequest(req, res){
if(req.method==='GET'){
var scope = 'this is the test scope';
res.json(scope); // TypeError: res.json is not a function
}
}).listen(port);
res.json() throws an error unless I use an express server
var app = express();
app.all('/*', function(req, res) {
if(req.method==='GET'){
var scope = 'this is the test scope';
res.json(scope); // OK!
}
}).listen(port);
I was pretty sure the json() function came with node. How do I send a response back to angular when using a native Node server?
res.json is not in the API for HTTP response.
The standard way would be to use res.write() (docs) and then res.end() (docs). But in your case, since you're not sending a lot of data you can use a shortcut and just use res.end() with a data parameter :)

Node, Express, domains, uncaught exceptions - still lost

I have been reading for hours on exception handling in Node. I understand the cons of using uncaughtException, I understand that shutting down the process is good for preventing any "unknown state" where "anything can happen". I understand that using domains is the way to go, and I understand how to properly implement domains, specifically Explicit Binding...
...but I'm still not getting any results for just basic error handling.
I would like to be able to just catch any uncaught exceptions for the purpose of logging. I don't mind killing the process or anything else deemed "undesirable". I just want a log.
I don't feel like I should have to wrap everything in a try/catch or use some library to emit errors... please correct me if I'm wrong and I will change my ways.
I am using Node and Express and I have the following simple code:
var express = require('express');
var domain = require('domain');
var serverDomain = domain.create();
serverDomain.on('error', function(err) {
console.log("SERVER DOMAIN ERROR: " + err.message);
});
serverDomain.run(function() {
var app = express();
app.get('/testing', function() {
app.nonExistent.call(); // this throws an error
});
var server = app.listen(8000, function() {
console.log('Listening on port %d', server.address().port);
});
});
The error shows up in the console, but the console never receives the "SERVER DOMAIN ERROR..." message. I have also tried wrapping the request/response in their own domain as well, to no avail. Even more disappointing is the fact that using the following does not work either:
process.on('uncaughtException', function(err) {
console.log('uncaughtException caught the error');
});
Am I doing something wrong? Where do I go from here? How can I catch the above error?
You can use connect-domain.
The problem is that the exception happens during Connect's routing, which has both a try/catch block around its execution, as well as a default error handler which prints out stack trace details when running in a non-production mode. Since the exception is handled inside of Express, it never reaches your outer layer for the domains to handle.
Here is an example why to use connect-domain package instead of domain.
http://masashi-k.blogspot.com/2012/12/express3-global-error-handling-domain.html
var express = require('express');
var connectDomain = require('connect-domain');
var app = express();
app.use(connectDomain());
app.get('/testing', function() {
app.nonExistent.call(); // this throws an error
});
app.use(function(err, req, res, next) {
res.end(err.message); // this catches the error!!
});
var server = app.listen(8000, function() {
console.log('Listening on port %d', server.address().port);
});
This happens because Express handles by itself the errors that may appear and in this way it simplifies your work. See Express Guide for error handling. You should use the structure below to handle the errors that may appear:
app.use(function(err, req, res, next){
console.error(err.stack);
res.send(500, 'Something broke!');
});

Node.js + socket.io: app on server not working correctly

I'm new to node.js and socket.io and tried to connect the server to the client with the example from http://socket.io/#how-to-use. (no localhost)
Server:
var app = require('http').createServer(handler)
, io = require('socket.io').listen(app)
, fs = require('fs')
app.listen(80);
function handler (req, res) {
fs.readFile(__dirname + '/index.html',
function (err, data) {
if (err) {
res.writeHead(500);
return res.end('Error loading index.html'+err);
}
res.writeHead(200);
res.end(data);
});
}
io.sockets.on('connection', function (socket) {
socket.on('message', function(msg){
console.log('Got text: '+msg);
socket.broadcast.send(msg);
});
socket.on('disconnect', function () { });
});
Client:
<html><head><script src="/socket.io/socket.io.js"></script>
<script>
var socket = io.connect();
socket.on('connect', function () {
alert('connected.');
socket.on('message', function (msg) {
// my msg
alert('message received: '+msg);
});
socket.send('hi');
});
</script>
</head><body>This is the content :)</body>
</html>
Google Chrome displays in the console:
Unexpected response code: 502
Also, after receiving every message, Chrome adds
GET http://[myServer]/socket.io/1/?t=1352313105809 socket.io.js:1659
Socket.handshake socket.io.js:1659
Socket.connect socket.io.js:1699
maybeReconnect
to the console.
Wheres the problem?
The examples from the How-To page all use port 80, which is common for serving websites.
However, you use port 8080 in your example.
Check your web browser's console if it even loads the socket.io script.
You may need to provide http://localhost:8080/socket.io/socket.io.js as explicit url and connect with io.connect('http://localhost:8080');
If the above does not work, please share some insight on what port your web server runs on.
There is no code to actually handle any incoming messages server-side in your (updated) example.
`socket.on('message', function(msg){
console.log('Got text: '+msg);
socket.send(msg);
});
should at the very least send the message back to the client - your alert is only triggered when the client receives a message. Does the node.js console output any incoming or sent messages? A few lines of my node.js console look like the following upon connecting.
debug - client authorized
info - handshake authorized ...
debug - setting request GET /socket.io/1/...
debug - set heartbeat interval for client ...
debug - client authorized for
debug - websocket writing 1::
debug - sending data ack packet

Categories

Resources