NodeJS Koa: How to map a hostname to a htttps server - javascript

I have created https server on port 3000 however, currently it is using IP in place of hostname (app.example.com). Hence all the requests happen at https://12.34.56.78:3000.
My current code:
let options = {
key: fs.readFileSync(path.resolve(process.cwd(), 'certs/abc.key'), 'utf8').toString(),
cert: fs.readFileSync(path.resolve(process.cwd(), 'certs/abc.crt'), 'utf8').toString(),
};
const httpsServer = https.createServer(options,app.callback())
.listen(process.env.PORT, "0.0.0.0", listening)
function listening () {
console.log("listening");
}
I want that all request to happen at https://app.example.com:3000.
How can I achieve this?
NOTE:
I have a registered hostname (for example app.example.com)
I have this hostname already running my html,css, and js static files on IIS
I want to use the same hostname for serving APIs of the same website. Hence same hostname

Related

How to use socket.io in localhost

I want to use socket.io in localhost which is my development environment:
client code:
const socket = io.connect('https://localhost:4000/');
socket.emit('trim-movie/go', data);
socket.on('trim-movie-response', trimResponse);
server :
const server = app.listen(port, () => console.log('server is online...'));
const io = socket(server);
io.on("connection", (socket) => {
socket.on('trim-movie/go', (data) => trimMovie(data, socket));
});
But I get this error:
socket.io.js?v=1:1415 GET
https://localhost:4000/socket.io/?EIO=4&transport=polling&t=OI2OmiX
404 (Not Found)
How to fix this?
Your client shows an https URL. Your server is starting an http server, NOT an https server because app.listen() only starts an http server. There's no way and https url will connect to an http server so these will ever match up.
Change the client to:
const socket = io.connect('http://localhost:4000/');
Or, if your page is already loaded from that same server, you can just use:
const socket = io();
and the client will get the domain and port from the URL of the containing web page.
Also make sure that the server-side port variable is set to 4000.

Customize cors-anywhere

I have deployed (hosted) cors-anywhere in Heroku, but i don't know how to customize it.
For example, I want to add a site link in whitelist.
I get data from this link: http://fmon.asti.dost.gov.ph/dataloc.php?param=rv&dfrm=null&dto=null&numloc=1&data24=1&locs[]=711
How will I do it? I have tried touching the server.js file:
// Listen on a specific host via the HOST environment variable
var host = process.env.HOST || '0.0.0.0';
// Listen on a specific port via the PORT environment variable
//var port = process.env.PORT || 443;
var port = process.env.PORT || 8080;
// Grab the blacklist from the command-line so that we can update the blacklist without deploying
// again. CORS Anywhere is open by design, and this blacklist is not used, except for countering
// immediate abuse (e.g. denial of service). If you want to block all origins except for some,
// use originWhitelist instead.
var originBlacklist = parseEnvList(process.env.CORSANYWHERE_BLACKLIST);
//var originWhitelist = ['http://fmon.asti.dost.gov.ph/dataloc.php','https://fmon.asti.dost.gov.ph/dataloc.php','http://fmon.asti.dost.gov.ph','https://fmon.asti.dost.gov.ph'];
var originWhitelist = parseEnvList(process.env.CORSANYWHERE_WHITELIST);
function parseEnvList(env) {
if (!env) {
return [];
}
return env.split(',');
}
// Set up rate-limiting to avoid abuse of the public CORS Anywhere server.
var checkRateLimit = require('./lib/rate-limit')(process.env.CORSANYWHERE_RATELIMIT);
var cors_proxy = require('./lib/cors-anywhere');
cors_proxy.createServer({
originBlacklist: originBlacklist,
originWhitelist: originWhitelist,
requireHeader: ['origin', 'x-requested-with'],
checkRateLimit: checkRateLimit,
removeHeaders: [
'cookie',
'cookie2',
// Strip Heroku-specific headers
'x-heroku-queue-wait-time',
'x-heroku-queue-depth',
'x-heroku-dynos-in-use',
'x-request-start',
],
redirectSameOrigin: true,
httpProxyOptions: {
// Do not add X-Forwarded-For, etc. headers, because Heroku already adds it.
xfwd: false,
},
}).listen(port, host, function() {
console.log('Running CORS Anywhere on ' + host + ':' + port);
});
but when I access the data and look at the console log, it returns a 403 error which is forbidden.
NOTE: When you say self hosted CORS it will only work for your site to
proxy. CORS setting on your server is for you not for the list of
sites you mentioned. They will be having their own CORS filters setup.
403 actually refers to the forbidden resource rather than a CORS Issue. Cors issue will look something like as follows:-
No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'yourUrl' is therefore not allowed access. The response had HTTP status code 400
For cors-anywhere the whitelisting code is pretty simple as mentioned below:-
// Listen on a specific host via the HOST environment variable
var host = process.env.HOST || '0.0.0.0';
// Listen on a specific port via the PORT environment variable
var port = process.env.PORT || 8080;
var cors_proxy = require('cors-anywhere');
cors_proxy.createServer({
originWhitelist: ['http://fmon.asti.dost.gov.ph'], // Allow all origins
requireHeader: ['origin', 'x-requested-with'],
removeHeaders: ['cookie', 'cookie2']
}).listen(port, host, function() {
console.log('Running CORS Anywhere on ' + host + ':' + port);
});
This should Ideally work for you with your application calling this somewhere.
If you are getting 403 while accessing this URL from your application
then be sure the URL you mentioned is protected and you must get
proper authentication done before requesting it.
I spent 3 days looking for the cause, got a 403 error for some sites and realized that the problem may be that they can not accept requests from "origin" different from theirs.
I just tried removing those headers on the proxy server and everything worked!
removeHeaders: ['origin', 'referer']

Kik bot will not reply

I have a Kik bot that I am hosting on my computer. I setup the configureation with the following code:
let request = require('request')
request.post('https://api.kik.com/v1/config',
{
"auth":{
"user":"bhs************",
"pass":"*******-*****-*****-****"
},
"headers":{
"User-Agent":"request"
},
"form":{
"webhook":"https://(my public ip):8080",
"features":{
"manuallySendReadReceipts":false,
"receiveReadReceipts":false,
"receiveDeliveryReceipts":false,
"receiveIsTyping":false
}
}
});
And here is the code for my actual bot:
'use strict';
let util = require('util');
let https = require('https');
let Bot = require('#kikinteractive/kik');
// Configure the bot API endpoint, details for your bot
let bot = new Bot({
username: 'bhs************',
apiKey: '*******-*****-*****-****',
baseUrl: 'https://(my public ip):8080'
});
bot.updateBotConfiguration();
bot.onTextMessage((message) => {
console.log("New Message")
message.reply(message.body);
});
// Set up your server and start listening
let server = https
.createServer(bot.incoming())
.listen(8080);
console.log("Server Running on port 8080")
I have setup port forwarding on my router to redirect to my computer with the internal and external port of 8080. I also have the protocol set to both TCP and UDP. Here is a photo if that setup:
My bot has stopped telling me that I need to Finnish setting it up every time I text it, but now it never says anything. Is there something that I'm doing wrong here?
It sounds like its not hitting your endpoint properly. I would suggested using ngrok to give yourself a public URL and it will forward to your local IP.
https://ngrok.com/

Configuring domain name instead of IP address while using restify in node app

I am using restify module to generate REST APIs for my application. I want to know how i could configure my domain name directly in this code. I want my ip_addr something like "domainname.com" instead of 127.0.0.1 .
var ip_addr = 'domainname.com';
var port = '80';
var connection_string = '127.0.0.1:27017/myapp';
var db = mongojs(connection_string, ['myapp']);
var jobs = db.collection("jobs")
var server = restify.createServer({
name : "myapp"
});
server.use(restify.queryParser());
server.use(restify.bodyParser());
server.use(restify.CORS());
server.listen(port ,ip_addr, function(){
console.log('%s listening at %s ', server.name , server.url);
});
I am getting an error EADDRNOTAVAIL whenever I use "domainname.com" instead of "127.0.0.1" can someone help, how can I configure it to my domain name in this node app?
There is some misunderstanding. It asks to specify IP address to listen to.
Example:
Server has address 100.1.1.2 and 100.1.1.3
mydomain.com is registered to 100.1.1.3
set ip_addr = '100.1.1.3'
In this case, the server will respond to all requests to this ip, and all domains registered to this IP. Connection through 100.1.1.2 will be timed out.
Shortly, if you want to listen to domainname.com, just specify the IP it is registered to.
And if you do not want to worry about the address and listen to all available network interfaces, then do not specify IP address at all:
server.listen(port, function() { .... Server API

Measuring traffic with node.js http-proxy

I wrote a small reverse proxy for hosting my applications on the same computer using http and node-http-proxy modules. For example:
I have:
proxy running on port 80
website1.com running on port 3000
website2.com running on port 3001
website3.com running on port 3002
If I access the website1.com domain, the proxy will serve the contents from server running on port 3000 using node-http-proxy.
But now I need to measure the bandwidth used for each domain (both incoming/outgoing, or at least outgoing)
I've tried listening for 'data' events on request object, but in documentation they said that readable events isn't emitted on IncomignMessage for some reason.
I wrote a little module for the "base" functionality too, it can be found here:
https://npmjs.org/package/reproxy
See example/example.js
So, how can I accomplish this measure, using the current setup?
The solution I found was setting and 'end' event on RoutingProxy object and grabbing the socket information in the event callback.
var proxy = new require('http-proxy').RoutingProxy();
proxy.on('end', function(req, res, response) {
var host = req.headers.host;
var bytesIn = response.socket._bytesDispatched;
var bytesOut = response.socket.bytesRead;
console.log('request to ' + host);
console.log('request: ' + bytesIn + ' bytes.');
console.log('response: ' + bytesOut + ' bytes.');
});
Note that this is not optimal solution, because the request size includes the headers added by the reverse proxy, such as "x-" headers.

Categories