I am using swagger-express-mw NPM package for creating REST services, when I run the project with "swagger project start" then it publishes the APIs over HTTP, how can I use HTTPS instead.
I have used HTTPS using vanilla npm packages as below:
var fs = require('fs');
var https = require('https');
var app = require('express')();
var options = {
key : fs.readFileSync('my.private.key'),
cert : fs.readFileSync('my.certificate.cer')
};
app.get('/', function (req, res) {
res.send('Yuhooo! Response over HTTPS!!! ');
});
https.createServer(options, app).listen(8443, function () {
console.log('Server started # 8443!');
});
But I am not sure how to achieve the same with swagger-express-mw, Below is the code snippet from my app.js which starts the listener. Not getting any option to use HTTPS as the protocol here
SwaggerExpress.create(configuration, function(err, swaggerExpress) {
if (err) { throw err; }
// install middleware
swaggerExpress.register(app);
var port = config.get('server.port') || process.env.PORT || 8080;
app.listen(port);
console.log('Server started at port %d', port);
});
var swaggerDoc = jsYaml.load(fs.readFileSync('./api/swagger/swagger.yaml'));
// Initialize the Swagger middleware for the api doc purpose
swaggerTools.initializeMiddleware(swaggerDoc, function (middleware) {
// Serve the Swagger documents and Swagger UI
app.use(middleware.swaggerUi());
});
app.listen is simply a shortcut you can use
SwaggerExpress.create(configuration, function(err, swaggerExpress) {
if (err) { throw err; }
// install middleware
swaggerExpress.register(app);
var port = process.env.PORT || 443;
https.createServer(options, app).listen(port, function () {
console.log('Server started # %s!', port);
});
});
Using Swagger 2.0 spec with middleware your swagger configuration file can be set to only accept certain schemes:
# Schemes is statically set here but will be overridden in app.js with
swagger object
schemes:
- https
You can review the specification and go to Fixed Fields: http://swagger.io/specification/
Related
I am creating a chaincode project , in which nodejs is consuming the chaincoe smartcontract.
My project structure includes index.js - swagger specs , app.js - to consumer swagger specs and bin/www - where http specification is defined .
I have defined http with basic auth and it works fine. For making all the services https secure , I have downloaded open ssl in my linux machine and have generated the certificate and the private key. (https://www.linuxhelp.com/how-to-install-and-update-openssl-on-ubuntu-16-04/)
I have made changes in the bin/www.js for the https part :
#!/usr/bin/env node
var app = require('../app');
var fs = require('fs');
var http = require('http');
var https = require('https');
require("dotenv").config();
var privateKey = fs.readFileSync('key.pem').toString();
var certificate = fs.readFileSync('cert.pem').toString();
var port = normalizePort(process.env.PORT || '8080');
app.set('port', port);
var hostname = process.env.HOSTNAME;
function normalizePort(val) {
var port = parseInt(val, 10);
if (isNaN(port)) {
// named pipe
return val;
}
if (port >= 0) {
// port number
return port;
}
return false;
}
https.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.write('Hello World!');
res.end();
}).listen(8080);
but this is not working . I have also imported the certificate and key in the mozilla. Request all to kindly help on this.
Thanks in advance.
You need to add the key and cert to the createServer function.
const options = {
key: fs.readFileSync('key.pem').toString();
cert: fs.readFileSync('cert.pem').toString();
}
https
.createServer(options, function (req, res) {
res.writeHead(200);
res.end("hello world\n");
})
.listen(443, function(){
console.log("Server listening on localhost:443");
});
Now, as #aditi said in the comments, the callback in createServer is a request handler. That means it will trigger when there is a request event. A request event is triggered by mostly HTTP requesting the server. So, if you open localhost:443 it will show you the "hello world" text.
If you want to console log something when the server is started (listing) you need to add the callback in the listen function. Which you have done.
it worked ,
I used
https.createServer(httpsOptions,app)
.listen(port,function(){
console.log("Inside HTTPS creation");
})
Thanks all.
I followed https://github.com/gsf/node-solr,installed node-solr with
npm install solr
then how to connect solr in 8080 port?
you can use solr-node npm packege it's really simple to configure. here is working example of calling solr from nodesjs and fetching data from solr
var SolrNode = require('solr-node');
var client = new SolrNode({
host: '<your host>',
port: '8983',
core: 'products',
protocol: 'http'
});
const express = require('express');
const app = express();
app.get('/getProduct',
function (req, res)
{
var strQuery = client.query().q('productId:9788700075740');
client.search(strQuery, function (err, result) {
if (err) {
console.log(err);
return;
}
console.log('Response:', result.response);
res.send(result.response);
});
});
app.listen(3000,
function () {
console.log('Example app listening on port 3000!') });
you can explore solr-node on npm https://www.npmjs.com/package/solr-node
var solr = require('solr')
var options = {
host: '127.0.0.1',
port: '8080',
core: 'bt', // if defined, should begin with a slash
path: '/solr/' // should also begin with a slash
};
// Create a client
var solrClient = solr.createClient(options);
put this options in the solr.createClient solved my question
I'm using Solr-client for node js.
npm install --save solr-client
// Load dependency
var solr = require('solr-client');
// Create a client
var client = solr.createClient();
// Add a new document
client.add({ id : 12, title_t : 'Hello' },function(err,obj){
if(err){
console.log(err);
}else{
console.log('Solr response:', obj);
}
});
I want to pull a URL from the DB and use it as the proxied URL. However the setup I've come up with initializes a new BrowserSync server for each URL, using incrementing port numbers.
Is there a way to accomplish this without initializing a new BrowserSync server every time?
Or should I be using another approach?
var bs = require("browser-sync");
var express = require("express");
var router = express.Router();
var app = express();
router.get("/", function(req, res){
var proxyUrl = getUrl() //get url from db (www.example.com)
bs.create("bs1").init({
notify: false,
open: false,
ui: false,
port: 10000,
proxy: proxyUrl
});
res.send();
});
app.use(router);
app.listen(8080, function(){
console.log('listening on *:8080');
});
The above is fine(ish) but is it good practice to be initializing a new server for every URL (potentially thousands)?
And is it safe to be exposing a new port number to every user of the system? (Can I mask this with a subdomain?)
Update
My end goal is to use a unique subdomain to refer to each proxy url.
For example:
sub1.mysite.com proxies www.example.com,
sub2.mysite.com proxies www.example2.com
Browser-sync will not work as the proxy is tie to server setup.
I use following packages:
express
express-http-proxy
vhost (express vhost)
const port = 8080;
var app = require('express')();
var proxy = require('express-http-proxy');
var url = require('url');
var vhost = require('vhost');
app.listen(port);
/* Assuming getUrl() will return an array of sites */
// var sites = getUrl();
// DO NOT put '/' at the end of site
var sites = [
'http://www.bing.com',
'http://samanthagooden.com',
'http://www.courtleigh.com'
];
var i = 0;
sites.forEach(site => {
i++;
var subDomain = 'sub' + i + '.mysite.com';
app.use(vhost(subDomain, proxy(site, {
forwardPath: (req, res) => url.parse(req.url).path,
intercept: (rsp, data, req, res, callback) => {
if (res._headers['content-type']) {
var contentType = res._headers['content-type'];
if (
contentType.indexOf('text') !== -1 ||
contentType.indexOf('javascript') !== -1
) {
// Replace link if content-type = text or javascript
var reg = new RegExp(site, 'g');
res.send(data.toString().replace(reg, ''));
} else {
res.send(data);
}
} else {
res.send(data);
}
}
})));
console.log(subDomain + ':' + port + ' proxy: ' + site);
});
The above example will create following proxies:
sub1.mysite.com:8080 proxy: www.bing.com
sub2.mysite.com:8080 proxy: www.example.com
Maybe I'm misunderstanding what you are trying to do, but Browsersync and express seems a bit overkill in this case, why not just use node-http-proxy with the native http module?
var http = require('http')
var httpProxy = require('http-proxy')
var options = ...
var proxy = httpProxy.createProxyServer(options)
var server = http.createServer(function (req, res) {
var proxyUrl = getUrl()
proxy.web(req, res, { target: proxyUrl })
})
server.listen(8080, function () {
console.log('listening on *:8080')
})
As per me If you want SAAS service using proxy is not the good idea to go is what am thinking.. if you are going with proxy for each client will create process with new port... My Solution is to create node server with listen localhost and map *.domain.com to the server..
If you are using individual database for each client :-
in node logic get cname from request host and use that reference to connect database.
Final Controller code would be..
var express = require('express');
var router = express.Router();
var MongoClient = require('mongodb').MongoClient;
/* GET home page. */
router.get('/', function(req, res, next) {
var client = req.subdomains[0];
console.log(client);
MongoClient.connect('mongodb://localhost:27017/'+client, function(err, db) {
if (err) {
throw err;
}
db.collection('app1').find().toArray(function(err, result) {
if (err) {
throw err;
}
console.log('data');
console.log(result);
});
});
res.render('index', { title: 'Express' });
});
module.exports = router;
~
~
In future if you get more clients you can implement node cluster or standard Ubuntu cluster using webservice
I'm working with node and express. I try to create a simple server using express.static. I have a file in the following folder on my server :
client/index.html
However, when I try this url : http://myServer.com/index.html, the server answers that :
Cannot GET /index.html
Here, you will find my used code :
var express = require('express');
var app = express();
app.use(express.static('client'));
/*
app.get('/', function (req, res) {
res.send('Hello World!');
});*/
var server = app.listen(8080, function () {
var host = server.address().address;
var port = server.address().port;
console.log('Example app listening at http://%s:%s', host, port);
});
My file index.html is available. I already used other way to keep this like by using
app.get('/index.html', function (req, res, next) {
var options = {
root: __dirname + '/client/',
dotfiles: 'deny',
headers: {
'x-timestamp': Date.now(),
'x-sent': true
}
};
res.sendFile("index.html", options, function (err) {
if (err) {
console.log(err);
res.status(err.status).end();
}
else {
console.log('Sent:', "index.html");
}
});
});
And this approach works.
You said that you were trying this URL:
http://myServer.com/index.html
But, your server is listening on port 8080, so you need to use this URL:
http://myServer.com:8080/index.html
or this:
http://myServer.com:8080
Because express.static() will automatically use index.html for the / path.
FYI, when I run your first block of code on my laptop with the proper URL, it works just fine. The browser shows me the contents of client/index.html where "client" is a sub-directory below where my app.js file is run from to start the server.
I've got a simple SockJS and Express server in nodejs. Now id like to add SSL support for these servers.
Here is my server code:
var sockjs = require('sockjs');
var my_http = require("http");
var https = require('https');
var fs = require('fs');
var options = {
key: fs.readFileSync('test/keys/key.pem'),
cert: fs.readFileSync('test/keys/cert.pem')
};
// Create a service (the app object is just a callback).
var app = express();
// Create an HTTP service.
http.createServer(app).listen(8008);
// Create an HTTPS service identical to the HTTP service.
https.createServer(options, app).listen(443);
var echo = sockjs.createServer({
log: function (severity, message) {}
});
echo.on('connection', function (conn) {
conn.on('data', function (message) {
conn.write(message);
});
conn.on('close', function () {
});
});
var server = my_http.createServer();
echo.installHandlers(server, {
prefix: '/echo'
});
server.listen(8081, '0.0.0.0');
var server_https = my_http.createServer(options);
echo.installHandlers(server_https, {
prefix: '/echo'
});
server_https.listen(443, '0.0.0.0');
app.get('/type/:channel', function (req, res) {
res.setHeader('Content-Type', 'application/json');
res.send("Hello");
res.end();
});
Problem is that i get the port already in use error:
Error: listen EADDRINUSE
I've got Nginx listening on 443 otherwise my site would not work on ssl.
Any ideas how to set this up?
Inside of your nginx config you should have your port listed in 'upstream'. In your case you probably have the same port listed under server. It shows that error when you do that. See below for proper configuration (If you change "listen 80" to "listen 8000" you'll see that error):
upstream app_yourAppName {
server 127.0.0.1:8000;
}
# the nginx server instance
server {
listen 80;
...
...
}