Express api res.jsonp returns double callback - node.js

I have an Express server running at port 8080 with this route
app.get('/api', function (req, res) {
res.jsonp('user API is running');
});
I open a browser window to
http://ec2-54-226-27-72.compute-1.amazonaws.com:8080/api?callback=hello
The response in the browser is
hello && hello("user API is running");
Why are there 2 hellos? Is this a proper JSONP response from Express and will it be processed correctly by a client?

Yes, that's the proper format. The purpose of the first hello is to make sure that the function hello exists on the client before trying to call it (an error would occur if the function did not exist).
There's a little bit of info about this in the preview chapter of the express book here. I just read it the other day.

Related

Showing video player on Node JS simple route

I have very simple node js application using express.
I have written route as below.
app.get("/", (req, res, next) => {
res.status(200).json("Application is up and running on port 4003!");
});
It was running quite well, was showing "Application is up and running on port 4003!" as expected but now, it suddenly showing up window as below and same for all other routes too.
I have not added video tag anywhere in my application.
What I did wrong?
Similarly I tried to run in postman and showing as below
Here is response header

how can I make an endpoint on express that never responds

I want write a test in mocha for how a timeout is handled.
I can set up a server that will never answer using netcat nc -kl 8080 (thanks https://stackoverflow.com/a/37465639/5203563).
However, since I already run an express server for all my other test endpoints inside mocha, it would be great if I could achieve the same thing with an express endpoint.
Does anybody know if that is possible?
Just don't return a response
var app = require('express')();
app.get('/fail', function(req, res) {
// does nothing
});
app.listen(8080);
Don't return the response from the route.
app.get('/', function(req, res) {});

Node.js - Download file after asynchronous functions are done

I have got a reverse proxy and a node.js server which sends a plain/text response back to the proxy which, in turn, does a bunch of front-end stuff 0% related to my problem.
The plain/text response comes from multiple asynchronous functions and the user is informed of the progress as each async function completes through the usage of
res.write("Example");
The problem is, the node.js server is supposed to prompt the browser for a download after all the async functions are complete. It's irrelevant how or where the file is downloaded.
I have tried to set the headers to Content-Disposition: attachment, but Node just throws something like Error: Can't set headers after they are sent.
Here's a code example:
app.post('/', function(req, res) {
res.statusCode = 200;
/*
Bunch of async functions
*/
res.download("some_file"); // This is included in the callback after all async functions are done
});
app.listen(3000, function() {
console.log('The server is running at http://whatever:3000/');
});
The async functions make use of eachSeries from the async module. This is another example of what I'm trying to accomplish:
async.eachSeries(func1,func2,function(err){
// something to prompt the user for download
});
Do I have to create another instance of express just to serve the download or is there some way to do everything within one express() instance?

What does Express.js do in the MEAN stack?

I have recently have gotten into AngularJS and I love it. For an upcoming project I am looking to use the MEAN stack (MongoDB, Express, Angular, Node). I'm pretty familiar with Angular and I have a modest understanding of the purposes of MongoDB and Node in the stack. However, I don't really understand what the purpose of Express.js is. Is it essential to the MEAN stack? What would you compare it to in a traditional MySQL, PHP, javascript app? What does it do that the other three components can't do?
Also, if someone wants to give their own take on how the four parts of the stack work together, that'd be great.
MongoDB = database
Express.js = back-end web framework
Angular = front-end framework
Node = back-end platform / web framework
Basically, what Express does is that it enables you to easily create web applications by providing a slightly simpler interface for creating your request endpoints, handling cookies, etc. than vanilla Node. You could drop it out of the equation, but then you'd have to do a lot more work in whipping up your web-application. Node itself could do everything express is doing (express is implemented with node), but express just wraps it up in a nicer package.
I would compare Express to some PHP web framework in the stack you describe, something like slim.
You can think of Express as a utility belt for creating web applications with Node.js. It provides functions for pretty much everything you need to do to build a web server. If you were to write the same functionality with vanilla Node.js, you would have to write significantly more code. Here are a couple examples of what Express does:
REST routes are made simple with things like
app.get('/user/:id', function(req, res){ /* req.params('id') is avail */ });
A middleware system that allows you plug in different synchronous functions that do different things with a request or response, ie. authentication or adding properties
app.use(function(req,res,next){ req.timestamp = new Date(); next(); });
Functions for parsing the body of POST requests
Cross site scripting prevention tools
Automatic HTTP header handling
app.get('/', function(req,res){ res.json({object: 'something'}); });
Generally speaking, Sinatra is to Ruby as Express is to Node.js. I know it's not a PHP example, but I don't know much about PHP frameworks.
Express handles things like cookies, parsing the request body, forming the response and handling routes.
It also is the part of the application that listens to a socket to handle incoming requests.
A simple example from express github
var express = require('express');
var app = express();
app.get('/', function(req, res){
res.send('Hello World');
});
app.listen(3000);
Shows the creation of the express server, creating a route app.get('/'... and opening the port to listen for incoming http requests on.
Express allows you to manage http request easily compared to vanilla js.
you need to the following to make a get request
const Http = new XMLHttpRequest();
const url='https://jsonplaceholder.typicode.com/posts';
Http.open("GET", url);
Http.send();
Http.onreadystatechange=(e)=>{
console.log(Http.responseText)
}
In express, you require express and use it and make http requests
const express = require("express")
const app =express();
app.get("url",callback function);
Express in a Node.js based framework which simplifies writing Server-side Code and Logic.
Adds a lot of utility features and offers additional functionality, and in general, makes things easier.
Express is middleware-based : It basically funnels incoming requests through a chain of middlewares (of steps) where we can do something with the request, read some data from it, manipulate it, check if the user is authenticated or basically send back a response immediately.
This middlewares chain allows us to write very structured code
Express is a nodejs Framework build upon the top of Http module with more usable and better functionalities like easy way to handle routes.
eg: Using HTTP
var http = require('http');
//create a server object:
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/html'}); // http header
var url = req.url;
if(url ==='/about'){
res.write('<h1>about us page<h1>'); //write a response
res.end(); //end the response
}else if(url ==='/contact'){
res.write('<h1>contact us page<h1>'); //write a response
res.end(); //end the response
}else{
res.write('<h1>Hello World!<h1>'); //write a response
res.end(); //end the response
}
}).listen(3000, function(){
console.log("server start at port 3000"); //the server object listens on port 3000
});
using Express:
var express = require('express');
var app = express();
app.get('/about',function(req,res)=>{
res.write('<h1>about us page<h1>'); //write a response
res.end();
})

Get response of Node.js Express app as a string

How does one get the response of an express app as a string given a request object?
In other words, I want a way to send a request object to an express app and receive its response as a string.
As code, I am looking for some implementation of the sendToThisApp method:
var app = express();
app.get( /* Some code here */ );
var request = // Some request object
var response = app.sendToThisApp(req)
console.log(response);
Thanks.
Here is the code for a simple Node.js Express app :
var app, express;
express = require('express');
app = express();
app.get('/', function(req, res) {
console.log(res);
res.end();
});
app.listen(8080);
In order to trigger a get request on this app, you need to run the app on node. Open a terminal and type this command:
node app.js
Then, you only need to start your favorite browser, go to localhost:8080, and look back at the log of the response in your terminal.
It looks like you're expecting things to happen synchronously that node and express want to handle asynchronously through callbacks.
But aside from that, I'm not really understanding what you're trying to do.
If you have the code for the node app, and you just want to see the response object as a string, then the easiest way to handle that is through the callback on the get.
app.get('/', function(req,res){
console.log(res);
}
But without knowing what you're actually after, I can't give better advice.

Resources