I'm trying to create an HTTPS server using node.js and and docker. I have already created the certificates and configured the app. But I don't know how to run the image docker. I am trying this, but it is not working.
Does anyone know how to do this?
sudo docker run --name cont_docker -p 443:3333 --link my-mongo:my-mongo user/docker_app
I am not using docker-compose
---> EDIT <---
The container is not crashing. It is not responding. In the app I get 'couold not connect to server'. I think it is not binding the port
const express = require('express');
const getRootPath = require('../helpers/get-root-path.helper');
var fs = require('fs');
const https = require('https'); // REQUIRE HTTPS
const privateKey = fs.readFileSync('private/key/path', 'utf8');
const certificate = fs.readFileSync('cert/key/path', 'utf8');
let _express = null;
let _config = null;
let _router = null;
let _credentials = null;
class Server {
constructor({ config, router }) {
_router = router;
_config = config;
_credentials = { privateKey: privateKey, certificate: certificate } // ADD CREDENTIALS
_express = express();
}
/*
This methods returns a promisse that will be in charge of initate the server.
*/
start() {
_express.use(express.static(`${this.getRootPath(__dirname)}/public`))
_express.use(_router)
_express.engine('html', require('ejs').renderFile)
_express.set('view engine', 'html')
return new Promise(resolve => {
const server = https.createServer(this._credentials, _express)
server.listen(_config.port, () => {
console.log(`App running on port ${_config.port}`)
resolve()
})
})
}
getRootPath(path) {
return getRootPath(path)
}
}
module.exports = Server
---> APP.JS <---
const container = require('./src/startup/container')
const server = container.resolve("app")
const { db_host, db_database } = container.resolve("config")
const mongoose = require('mongoose')
mongoose.set("useCreateIndex", true)
mongoose
.connect(`mongodb://${db_host}/${db_database}`, { useUnifiedTopology: true, useNewUrlParser: true, useCreateIndex: true, useFindAndModify: false })
.then(response => {
console.log(`Connected to Mongo! Database name: "${response.connections[0].name}" on "${response.connections[0].host}"`)
server.start()
})
.catch(console.log)
Related
As outlined in the title, I am having difficulty setting a http cookie to be used for auth purposes when tunnelling using ngrok.
The following code works fine (obviously with the relevant endpoints specified) when i am running a query from from localhost to a localhost endpoint in my dev environment but breaks down as soon as i start to query the ngrok tunnel endpoint.
Frontend api query (simplified as part of larger application)
function fetchRequest (path, options) {
const endpoint = 'http://xxx.ngrok.io'; // the ngrok tunnel endpoint
return fetch(endpoint + path, options)
.then(res => {
return res.json();
})
.catch((err) => {
console.log('Error:', err);
});
}
function postRequest (url, body, credentials='include') {
return fetchRequest(`${url}`, {
method: 'POST',
withCredentials: true,
credentials: credentials,
headers: {'Content-Type': 'application/json', Accept: 'application.json'},
body: JSON.stringify(body)
});
}
// data to be passed to backend for authentication
let data = {pin: pin, username : username};
postRequest('/',data)
Express server on Node.js with ngrok tunnel (app.js)
const express = require('express')
const session = require('express-session')
const cors = require('cors')
const router = require('./router');
const tunnel = require('./ngrok')
const app = express()
const port = process.env.PORT || 4001;
app.use(cors({
origin: 'http://localhost:3000'
credentials: true,
}))
app.use(express.json());
const expiryDate = new Date(Date.now() + 60 * 60 * 1000) // 1 hour
app.use(session({
secret: 'keyboard cat',
resave: false,
saveUninitialized: true,
cookie: {
httpOnly: true,
expires: expiryDate
// sameSite: 'none'
// secure: true
}
}))
app.use(router)
let useNGROK = true;
if (useNGROK) {
app.listen(port, () => {
console.log(`Example app listening at http://localhost:${port}`)
})
tunnel.createHTTPtunnel().then((url) => {
console.log(`New tunnel created with endpoint: ${url}`)
});
} else {
app.listen(port, () => {
console.log(`Example app listening at http://localhost:${port}`)
})
}
Ngrok configuration (ngrok.js)
const ngrok = require('ngrok');
const find = require('find-process');
const port = process.env.PORT || '3000';
const tunnel = {
createHTTPtunnel: async function () {
const list = await find('name', 'ngrok');
if (list.length > 0) {
let api = ngrok.getApi();
if (api == null) {
this.kill_existing_tunnel();
} else {
let open_tunnels = await ngrok.getApi().listTunnels();
return open_tunnels.tunnels[0].public_url;
}
}
let ngrok_config = {
proto: 'http',
bind_tls: false,
name: process.env.NGROK_NAME,
hostname: process.env.NGROK_CUSTOM_DOMAIN,
// host_header: 'rewrite',
authtoken: '',
region: 'eu',
};
return ngrok.connect({ ...ngrok_config, addr: port });
},
kill_existing_tunnel: async () => {
const list = await find('name', 'ngrok');
list.forEach((p) => {
try {
process.kill(p.pid);
console.log(`Killed process: ${p.name} before creating ngrok tunnel`);
} catch (e) {
console.log(e);
}
});
}
}
module.exports = tunnel;
** router & controller (router.js & controller.js respectively) **
*router.js*
const router = require('express').Router();
const example = require('./controller')
router.post('/', example.authenticate);
module.exports = router;
*controller.js*
async function authenticate (req, res) {
try {
res.send(JSON.stringify('trying to send cookie'))
} catch (e) {
console.log('Error', e)
res.sendStatus(500)
}
}
module.exports = {
authenticate
};
The following information is provided when inspecting the Set-Cookie response header in the network requests:
This Set-Cookie header didn’t specify a “SameSite” attribute and was defaulted to “SameSite=Lax” and was blocked because it came from a cross-site response which was not the response to a top-level navigation. The Set-Cookie had to have been set with “SameSite=None” to enable cross site usage.
Attempted fix 1//
If I add the following options to the cookie {sameSite: ‘none’, secure:true}, amend the ngrok config to set {bind_tls: true} and run https on my front end (using a custom SSL certificate as per the create react app documentation), and query the https tunnel, then no cookie is received in the response from the server at all (request is sent and response 200 is received but with no cookie).
Attempted fix 2//
I also tried to change the host_header option to rewrite in the ngrok config (to mirror a response from localhost rather than from ngrok) and this did not work.
Any help would be much appreciated as I have little experience and I am stuck!
Hello friends.
I need to continue my Nuxt JS work with SSL. However, after installation, I am getting the following error. I know the problem is because Node JS doesn't recognize the word "IMPORT". But I don't know how to solve the problem. Because I use Components as IMPORT all over the project. What is your suggestion?
Thank you very much in advance. 👋
package.json
"dev": "node server.js",
"nuxt": "^2.15.7",
"express": "^4.17.1"
ERROR IMAGE
error
SyntaxError: Cannot use import statement outside a module at compileFunction (<anonymous>)
nuxt.config.js
import axiosModule from './modules/axiosModule'
import momentModule from './modules/momentModule'
export default {
server: {
host: '0.0.0.0',
port: 3000,
},
......
server.js
const { Nuxt, Builder } = require('nuxt')
const expressServer = require('express')()
const thisHttp = require('http')
const thisHttps = require('https')
const thisFs = require('fs-extra')
const isProd = (process.env.NODE_ENV === 'production')
const isPort = 3000
let thisServer
if (isProd) {
const pKey = thisFs.readFileSync('./key.pem')
const pCert = thisFs.readFileSync('./cert.pem')
const httpsOptions = { key: pKey, cert: pCert }
thisServer = thisHttps.createServer(httpsOptions, expressServer)
} else {
thisServer = thisHttp.createServer(expressServer)
}
const nuxtConfig = require('./nuxt.config')
nuxtConfig.dev = !isProd
const nuxtServer = new Nuxt(nuxtConfig)
expressServer.use(nuxtServer.render)
const listen = () => { thisServer.listen(isPort, 'localhost') }
if (nuxtConfig.dev) {
new Builder(nuxtServer).build().then(listen()).catch(error => { console.log(error); process.exit(1) })
} else {
listen()
}
I fixed the situation manually. I did REQUIRE instead of IMPORT in Nuxt Config and used module.exports instead of Export Default. Even though I'm currently logging in via HTTPS, it's crossed out by Google Chrome.
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] };
I am trying to configure redirect-ssl node module into nuxt application
Referece : https://www.npmjs.com/package/redirect-ssl
But when i load site in browser it gives me error with message -> Cannot GET /
ref. https://prnt.sc/xqsc05
Site works on SSL without redirect module. But I want to forcefully redirect all non HTTP request to HTTPS. I tried .htaccess code but I think nuxt do not supports it.
There is no error into terminal.
Tried following into nuxt.config.js different ways as following.
serverMiddleware: ["redirect-ssl"],
Into server/index.js file added following code
const redirectSSL = require('redirect-ssl')
async function start () {
.
.
app.use(redirectSSL)
}
How can we use .htaccess file into nuxt. I tried placing into root or nuxt project setup, but that did not worked for me.
Also anyone know how to implement CDN into nuxt other than build:publicPath variable.
Any help or suggestion for redirect-ssl module or nuxt with htaccess please ?
Try out following way.
Into server/index.js
const redirectSSL = require('redirect-ssl');
const fs = require("fs");
const path = require("path");
const https = require('https');
const express = require('express');
const consola = require('consola');
const { Nuxt, Builder } = require('nuxt');
const app = express()
const pkey = fs.readFileSync(path.resolve(__dirname, 'domain_ssl.com.key'));
const pcert = fs.readFileSync(path.resolve(__dirname, 'domain_ssl.com.crt'));
const httpsOptions = {
key: pkey,
cert: pcert
};
// Import and Set Nuxt.js options
const config = require('../nuxt.config.js')
config.dev = false
async function start () {
// Init Nuxt.js
const nuxt = new Nuxt(config)
const { host, port } = nuxt.options.server
await nuxt.ready()
// Build only in dev mode
if (config.dev) {
const builder = new Builder(nuxt)
await builder.build()
}
// nuxt render and middleware
app.use(nuxt.render)
app.use(redirectSSL.create({ redirectPort: 443 }))
// Listen the server
app.listen(port, host)
consola.ready({
message: `Server listening on http://${host}:${port}`,
badge: true
})
https.createServer(httpsOptions,app).listen(443, host)
consola.ready({
message: `Server listening on https://${host}:${port}`,
badge: true
})
}
start()
Above one is for forcefully SSL redirection. And for CDN use this steps.
https://nuxtjs.org/docs/2.x/configuration-glossary/configuration-build
I want to host my frontend on Vercel (I'm using Nextjs) and since it doesn't support socket connections in it's API routes I decided to move this part of my app to Heroku. My problem is that when I use the server from my frontend in dev environment it works just fine, but when I deploy it to Heroku I get this error:
Access to XMLHttpRequest at 'https://my-socket-server.herokuapp.com/socket.io/?EIO=3&transport=polling&t=NMPkkyL' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
my server code looks like this:
import express from 'express';
import io, { Namespace } from 'socket.io';
import { PORT, menus, socketServerConfig, adminRoom } from './util/config';
const server = express().listen(PORT, () =>
console.log(`server running on port ${PORT}`)
);
const socketServer = io(server, socketServerConfig);
const attachSocketHandlers = (server: Namespace) => {
server.on('connection', socket => {
const handlers = {
'admin-log-in': () => {
socket.join(adminRoom);
},
'need-waiter': (table: Table) => {
server.to(adminRoom).emit('need-waiter', table);
},
'need-receipt': (table: Table) => {
server.to(adminRoom).emit('need-receipt', table);
},
order: (order: Order) => {
server.to(adminRoom).emit('order', order);
},
disconnect: () => {
socket.leaveAll();
},
};
Object.entries(handlers).map(([event, handler]) => {
socket.on(event, handler);
});
});
};
menus.forEach(menu => {
const namespacedServer = socketServer.of(`/${menu}`);
attachSocketHandlers(namespacedServer);
});
What I understood from the socket.io docs is that if you list no origins in the config it allows all origins to access the socket server.This is my socketServerConfig:
import { ServerOptions } from 'socket.io';
const defaultPort = 4000;
export const PORT = process.env?.PORT ?? defaultPort;
export const menus = ['more'];
export const adminRoom = 'admin';
export const socketServerConfig: ServerOptions = {
serveClient: false, // i don't serve any static files
};
this is how I connect from my frontend:
const url = 'https://my-socket-server.herokuapp.com/';
const io = connect(`${url}${menu}`);
I tried various solutions from SOF but I just can't get it to work, any help would be appreciated. Thanks in advance.
Try doing npm install cors and adding this to your server:
const cors = require('cors');
const whitelist = [
'http://localhost:3000',
YOUR FRONTEND URL
];
const corsOptions = {
origin: function (origin, callback) {
console.log('** Origin of request ' + origin);
if (whitelist.indexOf(origin) !== -1 || !origin) {
console.log('Origin acceptable');
callback(null, true);
} else {
console.log('Origin rejected');
callback(new Error('Not allowed by CORS'));
}
},
};
express().use(cors(corsOptions));
Hope this helped!