LocalHost to Domain Name using Express in React using nodejs - node.js

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.

Related

http2 in node.js, express, socket.io client

I am building a web app that uses a express and node.js in the backend. In my server.js file, I have the following code
const express = require("express");
const app = express();
const server = require("http").Server(app);
const io = require("socket.io")(server);
I recently discovered that there is http2 available, should I change the line 3 to
const server = require("http2").Server(app); instead?
If I switch to http2, is there anything else I need to specifically change that wasn't present in http1? And is the way of sending HTTP requests such as get or post any different from http1 to http2?
HTTP2 is more efficient and loads faster pages-Differences.
But I suggest you use https since its more secure and most of the browsers mark non https requests as insecure.
similar stack

Connecting frontend and backend MERN stack

How does the react client connect to the server via express? Many tutorials talk about Superagent and axios which is adding to my confusion. Are there any resources on server side routing in the context of react? thank you
In MERN stack, you do not necessarily have to think of the entire stack as a single entity. Mongo, ReactJS and NodeJS server can all work independently. And let us for easiness of understanding sake say all of them are on separate servers. That is we can have Mongo on one server, ReactJS on another server and NodeJS with express on a third server, then also it will be a MERN stack app.
How a MERN app work is as follows
For example, let us have an app that displays the details of all the students in a class. First, in the React app let us say you select a class, and then the React front-end will send a query to the nodejs server. The query will contain the particular class name. Now nodejs will send a query to the mongo db asking for the details of the students of that class which it will send back to the node server. The node server will then send the details to the front end and it will update it.
If you ask for connection as such, there can be no connection at all except for querying for data. Instead of using the reactjs front end you can use some other frontend and it will give you the same details. React, Mongo and Node, all are capable of working on their own in their respective fields.
Axios is a promise based HTTP client for the browser and node.js.
They are completely independent. Whether using axios, the native Javascript fetch, jQuery AJAX, etc...each of them runs in the browser and makes a GET/POST request to nodejs. You will have defined corresponding GET/POST routes within nodejs to respond to these requests and return JSON response data for them to consume.
I would start by forgetting about react altogether. Instead build an express API with various GET/POST routes that return JSON responses. Test with a simple client like postman. Once you have a handle on that, then start with a front-end Javascript framework to consume these services.
Here is a cut of my express+react api:
var express = require('express');
var router = express.Router();
router.get('/', function (req, res) {
res.render('index', {myjson: "myValue"});
})
module.exports = router;
Basically I am sending the json string to index.jsx, where the frontend is rendered.
Also I've set in express as:
app.set('views', __dirname + '/views');
app.set('view engine', 'jsx');
app.engine('jsx', reactViews.createEngine());
So the express server knows where React is.
Checkout the npm package Express-react-engine.
All the elements of the stack can be used independently, React , Node.Js, and MongoDB.
They can be installed in different servers and the communication is by using Fetch, Axios or any other tool.

Making requests to a node API from a different domain using HTTPS

I am serving a static page over HTTPS (https://example.com) that makes requests to a node API on a different domain (example-api.com).
My API is a standard express app using HTTP. Here's my setup code:
var express = require('express');
var app = exports.app = express();
var port = process.env.PORT;
exports.server = require('http').createServer(app).listen(port);
In the requests from my static page, I specify https://example-api.com as the URL. This works most of the time, but every once in a while (10% of the time?) Chrome errors out on the requests with:
net::ERROR_INSECURE_RESPONSE
Other users who've come across this issue (e.g. Failed to load resource: net::ERR_INSECURE_RESPONSE socket.io) seem to solve it by adding a credentials option to their createServer call, e.g.
var server = https.createServer(credentials, app)
So when I tried to implement this I came up with the following:
var fs = require('fs');
var options = {
key: fs.readFileSync('server-key.pem'),
cert: fs.readFileSync('server-cert.pem')
};
var express = require('express');
var app = exports.app = express();
exports.server = require('https').createServer(options, app).listen(port);
However this solution doesn't seem to work for me. When I try it the requests never make it to my app - even logs in app.use middleware don't appear.
What's really confusing is the fact that my setup seems to work most of the time.
Does anyone know how I can reliably make my requests?
Thanks and sorry in advance for my ignorance.
I struggled with this a bit as well. If you are on windows I have a solution that is a bit of a work around, but will allow you to serve your site, and NodeJS app over HTTPS.
In Windows, I created a reverse proxy in IIS to point at the nodeJS RESTful endpoint (i.e. nodeJS RESTful services == website.com:7000). Don't let reverse proxy scare you, its gravy.
To Implement:
Install IIS (if you haven't already)
Create your Self Signed Cert (assuming you know how to do that), or apply your Cert you are using now.
Install Application Request Routing
Open your website configuration, and go to URL Rewrite
For the rewrite stuff:
For Pattern: ^api(.*)
For rewrite: http://www.website.com:7000{R:1}
This basically takes any request from: https://www.website.com/api/someApiAwesomeness, and rewrites it to your nodejs App running at http://www.website.com:7000. Now you have an SSL RESTful app..
Good luck man I hope this helps!

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.

node js using express and restify together in one app

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.

Resources