node js using express and restify together in one app - node.js

I am using restify building apis, it works great. But I need to render some web pages as well in the same application.
Is it possible I can use express and restify together in one application?
this is the code for restify server in app.js
var restify = require('restify');
var mongoose = require('mongoose');
var server = restify.createServer({
name : "api_app"
});
server.use(restify.queryParser());
server.use(restify.bodyParser());
server.use(restify.CORS());
mongoose.connect('mongodb://localhost/db_name');
server.get('/', routes.index);
server.post('/api_name', api.api_name);
server.listen(8000 ,"localhost", function(){
console.log('%s listening at %s ', server.name , server.url);
});
how do I create express server in the same app.js?
Thanks

For all intents and purposes restify and express can't coexist in the same node process, because for unfortunate reasons, they both try to overwrite the prototype of the http request/response API, and you end up with unpredictable behavior of which one has done what. We can safely use the restify client in an express app, but not two servers.

I think restify, like express, simply creates a function that you can use as a request handler. Try something like this:
var express = require('express'),
restify = require('restify'),
expressApp = express(),
restifyApp = restify.createServer();
expressApp.use('/api', restifyApp); // use your restify server as a handler in express
expressApp.get('/', homePage);
expressApp.listen(8000);

If you need REST APIs and normal web pages, I don't think you need to stick to restify any more. You can always just use express, and build your API on it instead of restify, since express can do almost all things restify does.

I would solve this with a local api server, and a express proxy-route. Maybe not the best way with a bit of latency, but a possible solution how to separate your web frame from your api.

If you need to do a REST API and a Web application, I recommend you to use a framework that works on Express.
I created the rode framework, that is excellent to work with REST and works with Express.

Related

LocalHost to Domain Name using Express in React using nodejs

I build a nice React website for myself that's using Node Js and Mongodb on the backend. I finished everything and tested my mongodb atlas connection and everything is working fine on that side.
I was using Express to create a server, developing using localhost:4000. Now that I actually have a domain called let's say https:something.com using AWS amplify, I don't understand what modifications I have to make. Do I have to make Express listen to that url? How do I do that?
const express = require('express')
const app = express()
const port = 4000
var bodyParser = require('body-parser')
..... GET and POST REQUESTS
app.listen(port,()=>{console.log("Listening on port 8000")});
I've been searching a lot but I couldn't find anything useful. Or am I not supposed to be using Express? Am I supposed to do something like this:
app.listen(port,"IP");
You don't have to do anything, the custom domain is for frontend, so you don't need to change anything in your express code.

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.

How to mount a Sails.js app as express middleware

I would like to use Sails within a larger express based app. Most node.js MVC frameworks I have worked with you can mount as express middleware. Is this possible with Sails?
I want to do something like:
var express = require('express'),
app = express();
var mySailsApp = require('./mysailsapp');
app.use(mySailsApp);
While there are some active efforts to develop systems that would let Sails be more modularized, there's no way to use a Sails app as Express middleware. Sails works on top of Express, but not the other way around. However, you can use custom Express middleware with Sails--see this answer for an example.

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

Using everyauth with restify

I'm trying to use everyauth to handle authentication for a rest api created with restify.
But can't find a starting point. I'd expect to be doing something like:
var restify = require('restify');
var everyauth = require('everyauth');
var server = restify.createServer();
server.use(everyauth.middleware());
but restify does not accept the everyauth middleware.
How do I go about setting up restify and everyauth?
The issue you are having is restify does not and current will not have a middleware layer.
The below is from the author of restify
I've thought about this quite a bit, and the thing that worries me here is signing up for compatibility with connect evermore. I don't have control or input over what they decide to do. This seems more in the vein of "if it works, great".
I'm going to close this out with a "won't fix" for now :\
https://github.com/mcavage/node-restify/issues/89
What you can do is use connect and add the restify server on top of that, then you can use connect to manage your middleware like everyauth.
Here is a great sample of this, I have it working great on my system as-is.
// Restify server config here
var server = restify.createServer({
name: 'restify-test',
version: '1.0.0',
});
// ...
// Connect config here
var connectApp = connect()
.use(connect.logger())
.use(connect.bodyParser())
.use(connect.query())
.use(connect.cookieParser())
// And this is where the magic happens
.use("/api", function (req, res) {
server.server.emit('request', req, res);
});
connectApp.listen(8080);
https://gist.github.com/2140974
Then you can add everyauth to connect as per the documents.
Hope that helps.

Resources