Get response of Node.js Express app as a string - node.js

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.

Related

Parameter restriction with Node.js

What I want to do is check the script URL for a parameter & display the content of that parameter like:
www.mywebsite.com/mynodescript.js?parameter=i+am+new+to+node!
Now I want to display "I am new to node!" on browser screen and if the parameter is not present I just want to exit.
edit:
I found this code but I am not sure how to deploy it
var url = require('url');
var url_parts = url.parse(request.url, true);
var query = url_parts.query;
Note: i want to upload my script on heroku & want it to call it remotely
When you say you don't know how to deploy it, I'm assuming you don't have a http server setup yet?
Look at using Express (http://expressjs.com/). It's easy enough to get started with.
Create a file called app.js like this:
const express = require('express')
const app = express()
// This handles the path /mynodescript.js You can create a bunch of functions like this to handle different paths. See the express docs for more.
app.get('/mynodescript.js', (req, res)=>{
let parameter = req.query.parameter; // <-- Could also do let {parameter} = req.query This is where you would pull out your url parameters
if(parameter){
res.send(parameter); // <-- this sends it back to the browser.
}else{
res.status(422).end(); // <-- you can set a status here or send an error message or something useful.
}
})
app.listen(3000, () => console.log('Example app listening on port 3000!'))
Start the script using node app.js from the same directory.
Then open a browser and go to http://localhost:3000/mynodescript.js?parameter=i+am+new+to+node and you should see your parameter
Note that you will have to install express first npm install express --save
Note that you do not have to use express. There are quite a few http libraries available for nodejs. Or you can use the built-in http server (https://nodejs.org/api/http.html). It's good to get familiar with the NodeJS docs, but their http server is cumbersome to work with.

Host React and Express on the same server?

I am working on a react site that has a contact page. On the contact page there is a text field where you enter a message that will be sent to a specific email address.
Right now I'm just trying to set up express with my react app, the only thing I need Express for is this one feature.
In my react app I am doing
$.post('http://localhost:3030/API',{value:'hi'}, function(result) {
console.log(result);
});
And in my Express index.js file I'm doing
app.get('/API', (request, response) => {
console.log(request);
})
Just as a simple test to see if things are working properly.
When I run these both and attempt to execute my post function, I get the No 'Access-Control-Allow-Origin' header is present on the requested resource. error, which is basically saying that I can't make a request to a separate domain. The issue here is not that error, but the fact that I am running my Express server and react app on two different servers.
Is there a way to have them on the same server? I am very new to back-end development, any help would be very appreciated!
Yes, React runs on the client and Express is a Node.js framework. There's a pretty good chance you're using Express if you're running any boilerplate.
Here's a pretty good walkthrough on more complete routing.
https://medium.com/#patriciolpezjuri/using-create-react-app-with-react-router-express-js-8fa658bf892d
In several of my applications my routes look something like this:
//router.js--and I'm positive this is from some react-express boilerplate
var express = require('express');
var router = express.Router();
/* GET home page. */
router.get('/', function(req, res, next) {
res.render('index', { title: 'Express' });
});
const react = (req, res, next)=>{
res.render('react', {
title: 'React Application',
layout: false
});
};
router.get('/app', react);
router.get('/app*', react);
module.exports = router;
//app.js
...
app.use('/', routes); //<--this is the exported router.
...
If you want to be more simple it is probably something like:
let reactRoute = (request, response, next) => {
//render your react page however you're doing that.
}
express.use('/API', yourApiFunction)
express.use('/', reactRoute)
express.use('/*', reactRoute) //Wildcards are REALLY important if you're routing inside react.
You can also bypass things with a proxy but that tends to get more complex than you probably want. Also--keep in mind you don't have to stick to Node on the back-end if you're not comfortable with it. React is client side, I use it with a few production .NET apps, some PHP (lordy!), and, yes, a lot of Node servers.
to solve No 'Access-Control-Allow-Origin' header is present on the requested resource.
you've to use the cors middleware
go to the term
yarn add cors or npm i cors
in server.js
const cors = require("cors");
const express = require("express");
const app = express();
app.use(cors());

Why combine http module with express module

Hello guys i'm new to node js and started researching and working on some tutorials. I just want a better understanding or clarification on a doubt i had. So i came across the in built module http. This helps in creating a a basic web server. Now express module is a web framework that is built on top the http module that makes it easy using a fully wedged web server without reinventing the wheel. Now I came across this code:
var express = require( 'express' )
, http = require("http")
http.createServer( options, function(req,res)
{
app.handle( req, res );
} ).listen(8080);
But in express one could simply just do this
var express = require('express');
var app = express();
app.listen(8080, function() {
console.log('Listening on ' + 8080);});
What's the difference between both? Don't they both accomplish the same thing. If not what's the difference and advantage of using the first approach. Should one adhere to the first approach as it's a good programming practice. That's my doubt as i just want a clear understanding if there's any difference.
Why combine http module with express module
There's really no reason to create your own http server using the http module. Express will just do that for you with app.listen() just fine and save you little bit of typing.
If you were creating an https server, then you would need to use the https module and pass security credentials to https.createServer(...) in order to create a properly configured server. Express does not have the ability to create a properly configured https server for you automatically.
If you look at the Express code in GitHub for app.listen(), it shows this:
app.listen = function listen() {
var server = http.createServer(this);
return server.listen.apply(server, arguments);
};
So, there's really no difference (other than a little less typing) when you use app.listen() or create your own http server and then use app as the listener to that server.
So, these two code snippets are identical in function:
var app = require('express')();
app.listen(8080);
app.get('/', function(req, res) {
res.send("hello");
});
The above code is functionally identical to:
var http = require('http');
var app = require('express')();
http.createServer(app).listen(8080);
app.get('/', function(req, res) {
res.send("hello");
});
Of course, if you're trying to set up https servers or add custom options to the .createServer() method, then you will set up your own server first and then pass app to it as the listener. app.listen(...) is just a shortcut when the default http.createServer() works fine.

Post request to third party service from node server

What is the best way to send POST request from node server which has received the request parameter from a client? Reason I am asking for best practice because it should not affect the response time if multiple clients are calling the node service.
Here is the Backbone Model which sends the request to node server:
var LoginModel = Backbone.Model.extend({
url:'http://localhost:3000/login',
defaults: {
email:"",
password:""
},
parse: function(resp) {
return resp;
},
login: function() {
console.log('Here in the model'+JSON.stringify(this));
this.save();
}
});
var loginModel = new LoginModel();
Node Server
var http = require('http'),
express = require('express');
var app = express();
app.listen(3000);
app.post('/login', [express.urlencoded(), express.json()], function(req, res) {
console.log('You are here'); console.log(JSON.stringify(req.body));
//Send the post request to third party service.
});
Should I use something like requestify inside app.post() function and make a call to third party service?
I like superagent personally but request is very popular. hyperquest is also worth consideration as it resolves some issues with just using the node core http module for this.
Reason I am asking for best practice because it should not affect the response time if multiple clients are calling the node service.
First, just get it working. After it's working you can consider putting a cache somewhere in your stack either between your clients and your api or between your server and the third party api. I'm of the opinion that if you don't know exactly where you need a cache, exactly why, and exactly how it will benefit your application, you don't need a cache, or at the very least, you aren't prepared instrumentation-wise to understand whether your cache is helping or not.

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();
})

Resources