NodeJS Subdomain w/ vhost and greenlock-express - node.js

I'm new to Node and I want my website, dacio.app, working with subdomains for my college projects using vhost.
However, I need to have it secured due to the requirement for .app domains, so I'm using greenlock-express to automate it.
Don't be frontin', yo! TLS SNI 'giphy.dacio.app' does not match 'Host:
potatoes.dacio.app'
I've tried using the vhost example in the repo, but it doesn't look like server-static supports express apps.
Any tips on how to get this working? I keep hearing about reverse proxies, but I'm not sure if it's worth the effort as I don't even know if it would work - would it help?
server.js
#!/usr/bin/env node
'use strict';
// DEPENDENCIES
const express = require('express');
const vhost = require('vhost');
const path = require('path');
const glx = require('greenlock-express');
// MIDDLEWARE
const app = express();
const giphyApp = require('../giphy-search');
const potatoesApp = require('../rotten-potatoes');
const portfolioApp = require('../dacio.app');
// ROUTES
app.use(vhost('giphy.dacio.app', giphyApp));
app.use(vhost('potatoes.dacio.app', potatoesApp));
app.use(portfolioApp);
// GREENLOCK for HTTPS
glx.create({
version: 'draft-11',
server: 'https://acme-v02.api.letsencrypt.org/directory',
email: 'dacioromero#gmail.com',
agreeTos: true,
approveDomains: [ 'dacio.app', 'giphy.dacio.app', 'potatoes.dacio.app' ],
configDir: '~/.config/acme/',
app: app,
communityMember: false
}).listen(80, 443);

I've switched to using redbird which seems to accomplish everything I was hoping to do.
const path = require('path')
const proxy = require('redbird')({
port: 80,
letsencrypt: {
path: path.join(__dirname, '/certs'),
port: 9999
},
ssl: {
http2: true,
port: 443
}
});
proxy.register('dacio.app', 'http://localhost:8080', {
ssl: {
letsencrypt: {
email: 'dacioromero#gmail.com',
production: true,
}
}
});
proxy.register('giphy.dacio.app', 'http://localhost:8081', {
ssl: {
letsencrypt: {
email: 'dacioromero#gmail.com',
production: true
}
}
})
proxy.register('potatoes.dacio.app', 'http://localhost:8082', {
ssl: {
letsencrypt: {
email: 'dacioromero#gmail.com',
production: true
}
}
});

Related

http-proxy-middleware: pathFilter not working as expected

I am trying so setup a npm-based HTML development environment using two servers. One hosts my HTML app of static files (standard way: http://localhost:8080) while the other exposes an application api running locally(http://127.0.0.1:57146/api/someEntity). The latter is beyond my control.
Calling the api URLs directly from my app brings up CORS issues. So i want to setup a proxy that redirects my calls from http://localhost:8080/apiBase/someEntity to http://127.0.0.1:57146/api/someEntity... hoping to avoid the CORS problems that way.
I am using lite-server, which builds on top of Browsersync.
Since my static app files do not need redirection, they should not be affected by the proxy.To specify, which calls are redirected, i am trying to use the "pathFilter" field in the options. But i cannot get that functioning. Instead all calls are always proxied to http://127.0.0.1:57146. "pathRewrite" does not seems to work, either. So it seems like i am missing something basic here. What am i doing wrong?
Here is my config file:
//bs-config.cjs
const { createProxyMiddleware } = require('http-proxy-middleware');
const apiProxy = createProxyMiddleware({
target: "http://127.0.0.1:57146/",
pathFilter:"apiBase/",
pathRewrite: {
"apiBase/": "api/"
},
logger: "console",
logLevel: "debug"
});
module.exports = {
port: 8080,
index: "parent.htm",
startPath: "parent.htm",
cors: true,
server: {
baseDir: "./dist",
index: "parent.htm",
cors: true,
middleware: [ apiProxy ]
}
};
With the help of a (very) patient backend guy, i finally found a solution.
We could not get "pathRewrite" to work, but after getting the filter functioning (by changing some syntax), tweaking the paths ended up in a working setup.
//bs-config.cjs
const { createProxyMiddleware } = require('http-proxy-middleware');
const proxy_filter = function (path, req) {
const regx = new RegExp("/apiBase");
return path.match(regx);
};
const proxy_options = {
target: "http://127.0.0.1:57146/api/",
changeOrigin: true,
logger: "console",
logLevel: "debug"
}
const apiProxy = createProxyMiddleware(proxy_filter, proxy_options);
module.exports = {
port: 8080,
index: "parent.htm",
startPath: "parent.htm",
server: {
baseDir: "./dist",
index: "parent.htm",
middleware: [
apiProxy
]
}
};

node js express server postgres 500 internal server error

My api has stopped working, previously it worked fine and as far as i am aware I have changed nothing. When i tested my endpoint i received an internal server error.
Here is a link to my hosted api https://frozen-scrubland-34339.herokuapp.com/api
I have just checked some of my other apis and none are working either, same message. it appears my code isnt the issue but postgres itself?
Any help on what to do would be appreciated
When i tried to npm run prod to re-push it to heroku i received: 'Error: The server does not support SSL connections'
Again this was never an issue previously when it worked.
I imagine i have changed something with heroku itself by accident?
app.js
const express = require("express");
const app = express();
const apiRouter = require("./routers/api-router");
const cors = require("cors");
const {
handle404s,
handlePSQLErrors,
handleCustomError,
} = require("./controllers/errorHandling");
app.use(cors());
app.use(express.json());
app.use("/api", apiRouter);
app.use("*", handle404s);
app.use(handlePSQLErrors);
app.use(handleCustomError);
module.exports = app;
connection.js
const { DB_URL } = process.env;
const ENV = process.env.NODE_ENV || "development";
const baseConfig = {
client: "pg",
migrations: {
directory: "./db/migrations",
},
seeds: {
directory: "./db/seeds",
},
};
const customConfigs = {
development: { connection: { database: "away_days" } },
test: { connection: { database: "away_days_test" } },
production: {
connection: {
connectionString: DB_URL,
ssl: {
rejectUnauthorized: false,
},
},
},
};
module.exports = { ...baseConfig, ...customConfigs[ENV] };

Why do I have 404 error (Angular 2 and Node js)

I have a form on my site and I want to send the data from fields to my email. I am using nodemailer and node js for this things. But when I submit form I have an 404 error on POST request.
form-component:
this.http.post('api/sendForm',{
to: environment.contactUsEmail,
from: 'zzz',
subject: 'zzz',
mailInfo: contactUsData,
}
).subscribe(() => {
this.cooperationFormGroup.reset();
});
server.ts: (path:backend/server.ts) folder backend is near folder src
const express = require('express');
const bodyParser = require('body-parser');
const nodemailer = require('nodemailer');
const PORT = process.env.PORT || 3000;
const app = express();
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.post('api/sendForm', (req, res) => {
const payload = req.body;
const mailInfo = payload.mailInfo;
const transporter = nodemailer.createTransport({
service: 'gmail',
host: 'smtp.gmail.com',
secure: 'true',
port: '465',
auth: {
user: 'email',
pass: 'pass',
}
});
const text = [...];
const mailOptions = {
from: 'zz',
to: payload.to,
subject: payload.subject,
text: text.join('\n'),
};
transporter.sendMail(mailOptions, (error, info) => {
if (error) {
console.log(error);
} else {
console.log('Email sent: ' + info.response);
res.status(200).json({
message: 'successfully sent!'
})
}
});
});
app.listen(PORT, () => {
console.log(`Server is running in ${PORT}`);
});
I run server.ts in the folder backend using node server.ts and run angular app using npm start
As mentioned above in my comment: you need to pass the complete URL of your backend to post: use http://localhost:3000/api/sendForm instead of api/sendForm.
However, to manage different values during development and production, you might want to use environment.ts and environment.prod.ts:
environments/environment.ts:
export const environment = {
production: false,
urlToBackend: 'http://localhost:3000'
}
environments/environment.prod.ts:
export const environment = {
production: true,
urlToBackend: 'http://<IP>:3000'
}
service.ts:
While building the production build with npm run build, environment.ts will be replaced by environment.prod.ts as mentioned in the angular.json (see the object fileReplacements).
import { environment } from '../../environments/environment';
...
#Injectable()
export class AppService {
url = environment.urlToBackend;
constructor(private http: HttpClient) {
}
foo() {
return this.http.post(`${this.url}/api/sendForm`,{ ... });
}
}
My code is not accurate and you need to arrange it for your needs. However, I hope, you get the idea.
You need to mention the complete backend server URL in the first argument of the .post.
Change 'api/sendForm' to 'Your complete backend url'.
this.http.post( 'complete backend server url' ,
since you are running the node server on PORT 3000. Your backend URL will be http://localhost:3000/api/sendForm

Login failed for user using tedious

I am using tedious to connect to SQL Server Express, but I get a login failed error.
Server browser and SQL Server service are running, TCP/IP is enabled in network protocol. User name is enabled moreover I am able to login with .NET code but node.js code is really not working for me
var express = require('express'),
app = express(),
port = process.env.PORT || 3000;
var Request = require('tedious').Request;
var TYPES = require('tedious').TYPES;
var Tedious = require('tedious');
var config = {
userName: 'sa',
password: 'password',
server: 'localhost',
options: {
encrypt: true,
database: 'MediWorks',
instanceName: 'SQLEXPRESS01'
},
port : '1433'
};
var connection = new Tedious.Connection(config);
connection.on('connect', function(err) {
if (err)
{
console.log(err)
}
else
{
console.log("Connected");
}
});
Just for your information, tedious has deprecated the way you use config. A working example is like the following:
var config = {
server: "localhost",
authentication: {
type: "default",
options: {
userName: "yourusername",
password: "yourpassword"
}
},
};
tedious Github issue that mentions this.

Setup peerJS server combined with express

I'm trying to setup my own peerJS server following the readme on https://github.com/peers/peerjs-server#combining-with-existing-express-app
my code on server
port = process.env.PORT or 8080
http = require 'http'
express = require 'express'
app = express()
server = http.createServer app
app.use '/peerjs', ExpressPeerServer server, debug : on
server.listen port
server.listen 9000
my code on client
peer = new Peer
host : 'localhost'
port : 9000
secure : no
config :
iceServers : [ url : 'stun:stun.l.google.com:19302' ]
I get this error on client console
GET http://localhost:9000/peerjs/peerjs/id?ts=14150106969530.4679094860330224 net::ERR_CONNECTION_REFUSED
In case you are still looking for a way to establish your own peer server, then here is what I have done to make it work for me.
server.js
// initialize express
var express = require('express');
var app = express();
// create express peer server
var ExpressPeerServer = require('peer').ExpressPeerServer;
var options = {
debug: true
}
// create a http server instance to listen to request
var server = require('http').createServer(app);
// peerjs is the path that the peerjs server will be connected to.
app.use('/peerjs', ExpressPeerServer(server, options));
// Now listen to your ip and port.
server.listen(8878, "192.168.1.14");
Client side code
I guess, you should not have much problem in this, but if you are wondering what to put for certain parameters, then here is the initialization of the peer object:
var peer = new Peer({
host: '192.168.1.14',
port: 8878,
path: '/peerjs',
config: { 'iceServers': [
{ url: 'stun:stun01.sipphone.com' },
{ url: 'stun:stun.ekiga.net' },
{ url: 'stun:stunserver.org' },
{ url: 'stun:stun.softjoys.com' },
{ url: 'stun:stun.voiparound.com' },
{ url: 'stun:stun.voipbuster.com' },
{ url: 'stun:stun.voipstunt.com' },
{ url: 'stun:stun.voxgratia.org' },
{ url: 'stun:stun.xten.com' },
{
url: 'turn:192.158.29.39:3478?transport=udp',
credential: 'JZEOEt2V3Qb0y27GRntt2u2PAYA=',
username: '28224511:1379330808'
},
{
url: 'turn:192.158.29.39:3478?transport=tcp',
credential: 'JZEOEt2V3Qb0y27GRntt2u2PAYA=',
username: '28224511:1379330808'
}
]
},
debug: 3
});
This should help you to establish the connection.
One have to set a path to the server on their client side like this:
var peer = new Peer('your_peer_id', {host: 'localhost', port: 9000, path: '/peerjs'});
(this path has to be the same with the routing path to your ExpressPeerServer)

Resources