Node.js, Express.js, Angular.js: Hosting my own API - node.js

I am new to coding and I have a question about a small app that I created with angular.js that makes a post request to another express.js app.
It's a simple parentheses balance checker, you can find the whole code here:
https://github.com/OGsoundFX/parentheseschecker
The FrontEnd-Refactored folder contains the Angular.js app and the APItesting contains the express.js API.
The app is working, but I have only been using it locally. The API runs on localhost:3000 and the app on localhost:8080
But what if I want to make it public? How would I go about it? I don't really know where to start.
Where to host a node.js of express.js app. I read about AWS, would that be good, or are there better services?
I have a Wordpress website hosted on https://www.mddhosting.com/ but that wouldn't work, right?
My Angular app is calling the api locally at the moment, so I will probably have to change the API link that it is fetching:
ApiService.js
function ApiService($http) {
API = '//localhost:3000/parentheses';
this.getUser = (entry) => {
return $http
.post(API, { string: entry} )
.then(function (response) {
return response.data;
}, function (reason) {
// error
})
};
};
angular
.module('app')
.service('ApiService', ApiService);
In my API server.js
const http = require('http');
const app = require('./app')
const port = process.env.PORT || 3000;
const server = http.createServer(app);
server.listen(port);
I will definitely have to change API = '//localhost:3000/parentheses'; in my AngularJS app, but should I change const port = process.env.PORT || 3000; ?
I just need a little push start to help me clear some confusion.
Thanks!

Ensure you use application-level environment variables For example: To define the BASE_URL of your site for development and production separately. Doing so you don't have to make any configuration changes when you go live, it is a one-time process.
And if you are looking for free hosting services for pet projects Heroku is good and if you really want to make site go live for the end-users you may go for AWS EC2 instance or Heroku paid service both are good.

Related

How to connect my front end to a NodeJS Backend that's deployed publicly and not on localhost

I can connect them both when my NodeJS server is deployed on localhost PORT, for example
const PORT = 9000;
const app = express()
app.listen(PORT, () => console.log(`Server is running successfully on PORT ${PORT}`))
app.use(bodyParser.json({extended: true}))
app.use(cors())
app.use(bodyParser.urlencoded({extended: true}))
app.use('/', router)
And in my front end, I can do the following:
const url = 'http://localhost:9000'
...
const res = await axios.get(`${url}/post/${path}`)
This is just an example.
But what if I wanted to deploy my NodeJS server into a heroku application, for example randomname.herokuapp.com, and I want to do
const url = 'http://randomname.herokuapp.com:9000'
...
const res = await axios.get(`${url}/post/${path}`)
It obviously doesn't work. So I'd appreciate anyone who can help me do this.
Hello first of all if you deploy an app on heroku you will have to change port,you should add this to your code
app.listen(process.env.PORT || 3000,function(){
console.log("Server started at ${PORT}");
});
because heroku will not deploy on the same port as you did on your localhost.
Furthermore if i understand your question to link front with back end,in your code you should start building paths like
app.get("/")
app.post("/")
to handle get and post request to your home root and any other root.
Also in your front pages you need to take user input,if you want text field,checkbox or something else in a form and take them in your back end ,if it is on your home page for example.
app.post("/home",function(req,res){
const input=req.body.name;
}
I have also deployed apps on heroku and the main idea still remains same,you handle get,post request with these commands.You only change port and Pocfile to run your app on heroku.Get and post routes still remain same ("/home ,/info").
The link for your app is going to be:
"https://something_given_from_heroku.com" ,which will be given automatically from heroku.And you hit other routes like /home
I hope this help you,but check other posts to be sure.
I've been doing this myself, instead of starting with barebones up to skeleton and onwards just download this base web app which you can immediately deploy to Heroku.. Link is https://github.com/hubspot/basewebapp
from there, initiate a repo on github from that link and deploy on Heroku via deployment and with automatic deploys, change on VSC or GitHub, changes apply to the webpage/webapp on Heroku.
If you need any other help, feel free to contact me.. Been surfing Heroku apps for a few weeks already.
Check www.conid.dev for as far as I've published so far

Express-Socket.IO App isn't working with my Azure WebApp

For educational purposes I try to deploy an Express Server that is using Socket.IO. The Server should be able to deliver a static HTML Site that was built with React, answer with a "Hello Azure!" message whenever I make a GET Rest Call to http://localhost:4000/api/azure and whenever a new client connects to the site, all the other clients get a message announcing the new client.
const path = require('path');
const express = require('express');
const app = express();
const server = require('http').createServer(app);
const io = require('socket.io')(server);
const router = require('./api/azure');
const PORT = process.env.PORT || 4000;
io.on('connection', () => {
console.log('A new user has connected!')
io.emit('broadcast', 'A new user has connected');
});
app.use(express.json());
app.use('/api/azure', router);
app.use(express.static(path.join(__dirname, 'build')));
app.use(express.static('public'));
app.use('/', (_, res) => {
res.sendFile(path.join(__dirname, 'build', 'index.html'));
});
server.listen(PORT, () => {
console.log(`Listening to http://localhost:${PORT}`);
});
All this tasks are fulfilled without problems in localhost. The problem begins after this app is uploaded to one of my Azure WebApps.
Instead of delivering the message "Hello Azure!" when I call the https://mydomain.azurewebsites.net/api/azure it responses back with the HTML file.
The typical Socket.IO GET method for polling
https://mydomain.azurewebsites.net/socket.io/?EIO=4&transport=polling&t=SomeString
responses back with the HTML file, too.
Everything url extension that I give, gives me back the HTML file.
I barely know the basic stuff about WebApps. Maybe there is a configuration that I am forgetting? By the way I haven't done anything in the configuration except that I enabled the Websockets in the WebApp config.
This never happened before. The only difference is that right now I am using a free-tier just to test. Could it be that? If not, what am I doing wrong?
Thank you for your time!
To begin with, try turning the Web Socket config off as it applies to an IIS setting which tends to contradict with the Node.js websocket implementation.
If this doesn't help, try and force the transport layer to use Websockets and SSL.
io.configure(function() {
// Force websocket
io.set('transports', ['websocket']);
// Force SSL
io.set('match origin protocol', true);
});
Also, you cannot use arbitrary ports (port 4000 in your case) on services like App Service. Your app will be provided a port via process.env.PORT. So ensure that you are refering to the correct port from your log message. You should be able to see these in your log stream.
Also note, that Azure has launched a fully managed service called Web PubSub to power your apps with Web Sockets. The app service web socket implementation does not scale horizontally, this where Web PubSub will help you.
https://azure.microsoft.com/en-in/blog/easily-build-realtime-apps-with-websockets-and-azure-web-pubsub-now-in-preview/

Firebase functions: koa.js server how to deploy

I already have an app written in MERN stack with koa server prepared build version. My main node file to run by node server.js command to start the whole app looks like this.
In every tutorial, I see that I need to add functions.https.request etc. in the beginning of coding (or at least to suppose doing it).
How could I host my app on firebase the same as I could on heroku - with whole server side?
It is possible to host Koa app using firebase functions, I figure it out after some Googling and analyzing.
This is a piece of code from my project, it is now hosted with firebase functions:
const Koa = require('koa');
const app = new Koa();
// ... routes code here ...
// This is just for running Koa and testing on the local machine
const server = app.listen(config.port, () => {
console.log(`HITMers-server is running on port ${config.port}`);
});
module.exports = server;
// This export is for Firebase functions
exports.api = functions.https.onRequest(app.callback());
You can see the docs and tutorial video for more information.
By the way, here is another example to deploy Koa to now.sh version 2.
You can actually skip the listen call entirely, and use app.callback().
This seems to make more sense than listening on a random port that never actually gets hit.
const functions = require('firebase-functions');
const app = new Koa();
... // set up your koa app however you normally would
app.use(router.routes());
module.exports.api = functions.https.onRequest(app.callback());
You can run an express application using firebase hosting to serve dynamic content via firebase functions. You cannot, however, use Koa.js currently. The functions.https.onRequest requires you to pass an HTTP request handler or an express app returned from express().
Here is the relevant article from Firebase about serving dynamic content from functions.
https://firebase.google.com/docs/hosting/functions
Here is a video tutorial from Firebase on using express.
https://www.youtube.com/watch?v=LOeioOKUKI8
To anyone looking for koa Google Cloud Functions, Here is my working version in typescript
import Koa from 'koa';
import Router from 'koa-router';
import type { HttpFunction } from '#google-cloud/functions-framework/build/src/functions';
const app = new Koa();
const port = process.env.PORT || 3001;
const router = new Router();
router.get('/', async (ctx) => {
ctx.body = 'Hello World!';
});
app.use(router.routes());
// For development on local
if (!isCloudFunctions()) {
app.listen(port, () => {
console.log(`Server running on port ${port}`);
});
}
export const helloWorldApi: HttpFunction = app.callback();
function isCloudFunctions(){
return !!process.env.FUNCTION_SIGNATURE_TYPE;
}
For deployment:
gcloud functions deploy test-koa-function --entry-point=helloWorldApi --runtime nodejs16 --trigger-http --allow-unauthenticated
You can't deploy and run an arbitrary node app on Cloud Functions. You have to make use of the different types of triggers that are defined by the product.
See the Cloud Functions for Firebase main page to see the list.
Cloud Firestore Triggers
Realtime Database Triggers
Firebase Authentication Triggers
Google Analytics for Firebase Triggers
Crashlytics Triggers
Cloud Storage Triggers
Cloud Pub/Sub Triggers
HTTP Triggers

Between Node.JS and Express, can someone explain where the Web Server fits in?

I've recently started server-side development using Node JS and Express but i'm getting confused as to how it all works. From my understanding, The web serve stores the website and returns the pages as they're requested from the browser. Apache is a web server and you would use that for a stack like XAMPP. ASP.NET is a framework that uses IIS Web Server and communicates with that.
But with Node, where's the server? Node is runtime environment and is USED to CREATE a server and Express is a web FRAMEWORK to help with server http requests but what/where is the actual web SERVER? Maybe i'm just not understanding web servers or something? Someone please clarify!
For Node, we do not need a web server like Apache or a container that sort of, node can listen to a port and act as a server itself,
and express is web application framework for Node which provides set of features to make life easier.
for a vague comparison, if Node is a telephone then Node + express will be a smartphone. - both can do same stuff but latter have more convenient features.
see below two example of creating a server which listen to a port 3000,
In node:
const http = require('http')
const requestHandler = (request, response) => {
console.log(request.url)
response.end('Hello Node.js Server!')
}
const server = http.createServer(requestHandler)
server.listen(3000,() => console.log("app started"));
Node + express
const express = require('express');
const app = express();
app.get('/', function (req, res) {
res.send('Hello express !')
})
app.listen(3000,() => console.log("app started"));
Both does the same thing, but with express things are easier.

Firebase Hosting with own server node.js

I have webapp with firebase database. I would like hosting the app on firebase. My app has own server nodejs and using websockets. How can I host my app on Firebase? And how can I run my own server on Firebase?
I think your question is quite simple. And the answer is also simple: no, you can't.
Firebase only serves static files. You need to try heroku, codeship, etc for that.
I'm not sure what exactly you are looking for. I'll assume it's one of these two:
you want to run the node.js scripts on Firebase's server
There is no way to run your own code on Firebase's servers.
you want to run the node.js scripts on your own server and have them interact with your Firebase data
Firebase has a node.js package that allows you to talk to its BaaS service from your own node scripts. See the node.js section in Firebase's quickstart and the npm package for Firebase.
You can use Google Cloud Functions to do most task processing in a serverless style: https://firebase.google.com/docs/hosting/functions
I'm using it to dynamically load javascript based on req.url.
With Firebase functions, yes you can. You can watch this tutorial from Google, it's very clear and easy to catch up.
Node.js apps on Firebase Hosting Crash Course - Firecasts
Firebase Hosting allows you to use Cloud Functions to perform server-side processing. This means that you can support dynamic generation of content for your Firebase Hosting site.
Documentation
Firebase Functions is the way to go.
Example:
Setup /index.js in your project with expressjs listening on port what ever you want. F.e. 3000
const app = express()
const port = 3000
...
app.get('/', (req, res, next) => {
... hier your code to handle request
})
...
app.listen(port, () => {
console.log(`app listening at port = ${port}`)
functions.logger.info("Application started", {structuredData: true});
})
Export your function with reference to express-app:
exports.api = functions.https.onRequest(app)

Resources