Trying to set up Node.js application under subdomain on Windows Server - node.js

I'm attempting to set up my first Node.js application on Windows Server. The application runs fine with the command:
node index.js
It'll run my application on localhost:8000. However, I want it to run on a subdomain on port 80, so I tried the following command:
set PORT=80 && set HOST=api.mydomain.com && node index.js
And here is my index.js file, which handles setting the PORT and HOST in the app.listen command:
import express from 'express';
import bodyParser from 'body-parser';
const expressJwt = require('express-jwt');
const config = require('./environment.json')[process.env.NODE_ENV || 'development'];
const app = express();
const port = +process.env.PORT || 8000;
const host = process.env.HOST || 'localhost';
// Skipping app.use commands...
app.get('/', root);
app.listen(port, host, 34, err => {
if (err) return console.error(err);
return console.log(`Server is listening on ${port}`);
});
Unfortunately, using a subdomain errors:
events.js:187
throw er; // Unhandled 'error' event
^
Error: getaddrinfo ENOTFOUND api.mydomain.com
at GetAddrInfoReqWrap.onlookup [as oncomplete] (dns.js:60:26) Emitted 'error' event on Server instance at:
at GetAddrInfoReqWrap.doListen [as callback] (net.js:1485:12)
at GetAddrInfoReqWrap.onlookup [as oncomplete] (dns.js:60:17) { errno: 'ENOTFOUND', code: 'ENOTFOUND', syscall: 'getaddrinfo',
hostname: 'api.mydomain.com ' }
What is the proper way to configure the Node.js application to run under the subdomain? If I were using IIS it'd be as simple as adding additional Bindings, but now I'm in Node.js land instead so have no idea how to go about it.

host
No for your application to run locally with this domain name you must modify the host configurations to make api.mydomaine.com correspond to the ip address 127.0.0.1 on your machine

I ended up just running it under IIS, using a reverse proxy. Then I could use IIS to set up the subdomain binding, much simpler...
https://dev.to/petereysermans/hosting-a-node-js-application-on-windows-with-iis-as-reverse-proxy-397b

Related

Plesk Already in use NODEJS

I have this problem on my server using PLesk ,
Specs: Ubuntu 18.0.40.1 , Plesk
I tried to change the port to random numbers and the same results, says already in use.I would like to do the deploys well to be able to learn, I can try elsewhere but it is a priority to do it in plesk
Nodejs Config:
const app = express();
//CORS
const domainWhiteList = [process.env.ORIGIN1,process.env.ORIGIN2]
app.use(cors({
origin: function (origin, callback) {
console.log(origin)
if (!origin || domainWhiteList.includes(origin)) {
return callback(null,origin)
}
return callback('Not allowed by CORS ' + origin)
}
}));
//Uso de cookies
app.use(cookieParser());
//Activar JSON Body Leer
app.use(express.json());
//Api de Inicio de Sesion
app.use("/api/v1/auth", authRouter);
//Api Links
app.use("/api/v1/links", linkRouter)
//Port Default
const PORT = process.env.PORT || 5000;
//App se ejecuta en este port
app.listen(PORT, () => {console.log("Server is running on port:"+ PORT + " http://localhost:"+ PORT)});
Error: listen EADDRINUSE: address already in use :::4657
at Server.setupListenHandle [as _listen2] (node:net:1740:16)
at listenInCluster (node:net:1788:12)
at Server.listen (node:net:1876:7)
at Function.listen (/var/www/vhosts/vexshe.fun/proyects.vexshe.fun/node_modules/express/lib/application.js:635:24)
at file:///var/www/vhosts/vexshe.fun/proyects.vexshe.fun/index.js:47:5
at ModuleJob.run (node:internal/modules/esm/module_job:193:25)
Emitted 'error' event on Server instance at:
at emitErrorNT (node:net:1767:8)
at process.processTicksAndRejections (node:internal/process/task_queues:82:21) {
code: 'EADDRINUSE',
errno: -98,
syscall: 'listen',
address: '::',
port: 4657
}
Node.js v19.6.0```
I try to deploy my proyect in plesk , i do it in render and works fine but in plesk doesnt work.

express - mongodb connection issue

I setup a cluster in my mongodb atlas database and to my best of knowledge i did everything right and copied the right to my application using sample_mflix database
in my .env file
MOVIEREVIEWS_DB_URI=mongodb+srv://driiisdev:password123#cluster1.ektx7.mongodb.net/sample_mflix?retryWrites=true&w=majority
PORT=5000 //starting port of server
in my index.js file
import app from "./server.js"
import mongodb from "mongodb"
import dotenv from "dotenv"
dotenv.config();
const uri = process.env.MOVIEREVIEWS_DB_URI;
const client = new mongodb.MongoClient(uri);
const port = process.env.PORT||8000;
(async ()=>{
try{
//Connect to the MongoDB cluster
await client.connect();
app.listen(port, ()=>{
console.log("server is running on port:" +port);
})
}catch(e){
console.error(e);
process.exit(1)
}
})().catch(console.error);
in my server.js
import express from 'express'
import cors from 'cors'
import movies from './api/movies.route.js'
const app = express()
app.use(cors())
app.use(express.json())
app.use("/api/v1/movies", movies)
app.use('*', (req,res)=>{
res.status(404).json({error:"not found"})
})
export default app
on running nodemon server , the error i get
Error: querySrv ECONNREFUSED _mongodb._tcp.cluster1.ektx7.mongodb.net
at QueryReqWrap.onresolve [as oncomplete] (node:dns:213:19) {
errno: undefined,
code: 'ECONNREFUSED',
syscall: 'querySrv',
hostname: '_mongodb._tcp.cluster1.ektx7.mongodb.net'
}
The error indicates a possible SRV lookup failure.
Could you try using the connection string from the connection modal that specifies all 3 hostnames instead of the SRV record? To get this, please head to the Atlas UI within the Clusters section and follow the below steps:
Click Connect on the cluster you wish to connect to
Select Connect your application
Choose Node.JS for the Driver option
Choose the *Version 2.2.12 or later for the version option
Copy and use the connection string which should begin with the following format:
mongodb://:....
Replace the original connection string you used with the version 2.2.12 or later node.js connection string copied from the above steps and then restart your application.
//also in the .env file
// remove the comment after the PORT is assigned, as .env reads comment and will return error
PORT=5000

http request to a different app in a different port

I have 2 nodejs apps one running in port 8000 that only returns "hello"
and another app running on port 3000 that makes a simple http request to the first app
var http = require('http');
var r = http.get({
host: 'localhost',
path: '/',
port: '8000'
},
function(response) {
var body = '';
response.on('data', function(d) {
body += d;
});
response.on('end', function() {
console.log(body);
});
});
the console log returns
events.js:141
throw er; // Unhandled 'error' event
^
Error: connect ECONNREFUSED 127.0.0.1:8000
at Object.exports._errnoException (util.js:874:11)
at exports._exceptionWithHostPort (util.js:897:20)
at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1063:14)
What´s the problem here?
the first app is running correctly in http://localhost:8000/ but for some reason
when the second app makes a request to the first app I get the error I posted above. thanks for your help.
Seems like first app (on port 8000) is not reachable or not started at the moment, when second app sends request.

When I try to do a https post request in node, I get a getaddrinfo ENOTFOUND error

The full error is this:
events.js:160
throw er; // Unhandled 'error' event
^
Error: getaddrinfo ENOTFOUND https://api.instagram.com https://api.instagram.com:443
at errnoException (dns.js:28:10)
at GetAddrInfoReqWrap.onlookup [as oncomplete] (dns.js:79:26)
and my code to get just the error is this:
var express = require('express');
var app = express();
var https = require('https');
app.get('/oauth/ig', function (req, res) {
var options = {
hostname: 'https://api.instagram.com',
path: '/oauth/access_token?client_secret=myClientSecret&grant_type=authorization_code&redirect_uri=http://localhost:1992/oauth/ig&code='+req.query.code,
method: 'POST',
};
var igRequest = https.request(options, (response) => {
res.send("response");
});
})
I am using nodejs and am trying to do the Instagram OAUTH.
hostname should be just the host name, not including the protocol:
hostname: 'api.instagram.com',
In addition to the answer by mscdex, it's worth mentioning that
there are already working modules on npm that do that, e.g.:
passport-instagram
passport-instagram-token
instagram-node
Maybe you could use one of them instead of rolling your own solution.
There is nothing wrong about rolling your own solution but if you can't get it right, sometimes it's just not worth the hassle.
Two of the modules that I recommended above are Instagram strategies for Passport, which is a de facto standard way of doing authentication in Node, with over 300 different strategies available that you can use in a unified way.
See the Passport website for more info.

Error in http-proxy module : Must provide a proper URL as target

I'm new in Node.JS and deployed the first application on VPS.
After running on port 8000, i decided create a http-proxy for forward each domain to its specific port .
I worte a little application like here :
var http = require('http'),
httpProxy = require('http-proxy');
var option = {
router : {
'domain.com' : 'http://88.198.86.100:8000'
}
};
var proxyServer = httpProxy.createServer(option);
proxyServer.listen(80);
88.198.86.100 is my server ip.
So, my problem here is shown , when i typed 88.198.86.100 in my browser PC (Google Chrome), my proxy application in server was carshed and gave this error :
C:\Users\Administrator\Desktop\Nodejs\node_modules\http-proxy\lib\http-proxy\index.js:119
throw err;
^
Error: Must provide a proper URL as target
at ProxyServer.<anonymous> (C:\Users\Administrator\Desktop\Nodejs\node_modules\http-proxy\lib\http-proxy\index.js:68:35)
at Server.closure (C:\Users\Administrator\Desktop\Nodejs\node_modules\http-proxy\lib\http-proxy\index.js:125:43)
at emitTwo (events.js:106:13)
at Server.emit (events.js:191:7)
at HTTPParser.parserOnIncoming [as onIncoming] (_http_server.js:546:12)
at HTTPParser.parserOnHeadersComplete (_http_common.js:99:23)
error: Forever detected script exited with code: 1
I want to someone enter IP server into the each browser, my application will not crash.
//below code works for me
var httpProxy = require('http-proxy')
var proxy = httpProxy.createProxy();
var options = {
'foo.com': 'http://foo.com:8001',
'bar.com': 'http://bar.com:8002'
}
require('http').createServer(function(req, res) {
proxy.web(req, res, {
target: options[req.headers.host]
});
}).listen(80);

Resources