How to set custom port number on swagger-api? - express

I created the project using the following command and chose Express framework.
swagger project create api-name
project starts on http://localhost:10010/
But I set my custom port number 10020.
Starting: /home/rajan/Documents/cse-4-1/web-lab/api/BankApi/app.js...
project started here: http://localhost:10010/
project will restart on changes.
to restart at any time, enter `rs`
try this:
curl http://127.0.0.1:10020/hello?name=Scott
My question is why second and last line showing different port number?
My app.js file:
'use strict';
var SwaggerExpress = require('swagger-express-mw');
var app = require('express')();
module.exports = app; // for testing
var config = {
appRoot: __dirname // required config
};
SwaggerExpress.create(config, function(err, swaggerExpress) {
if (err) { throw err; }
// install middleware
swaggerExpress.register(app);
//var port = process.env.PORT || 10010;
var port = 10020;
app.listen(port);
if (swaggerExpress.runner.swagger.paths['/hello']) {
console.log('try this:\ncurl http://127.0.0.1:' + port + '/hello?name=Scott');
}
});

I also set the port number on yaml file. Then fixed it.

Related

Unable to verify the first certificate Next.js

I am trying to build a new application.
It accesses one API to get some data over HTTPS.
Status2.getInitialProps = async () => {
console.info('ENTERRRRRRRR')
const res = await fetch('https://test.com/api/v1/messages', {
method: 'get',
headers: {
'Authorization': 'Bearer ffhdfksdfsfsflksfgjflkjW50aXNocjEiLCJpYXQiOjE2MDc1ODIzODQsImF1ZCI6InJlY3J1aXRpbmdhcHAtMTAwMC5kZXZlbG9wLnVtYW50aXMuY29tIiwiaXNzIjoicmVjcnVpdGluZ2FwcC0xMDAwLmRldmVsb3AudW1hbnRpcy5jb20ifQ.0jqPutPOM5UC_HNbTxRiKZd7xVc3T5Mn3SjD8NfpEGE',
'Accept': 'application/vnd.api+json'
}
}
)
}
When the browser tries to access this API then it gives me the following error:
Server Error
FetchError: request to https://test.com/api/v1/messages failed, reason: unable to verify the first certificate
This error happened while generating the page. Any console logs will be displayed in the terminal window.
C
To solve this issue I followed this but when tried it, it gave me another error:
'NODE_TLS_REJECT_UNAUTHORIZED' is not recognized as an internal or external command,
operable program or batch file.
The NODE_TLS_REJECT_UNAUTHORIZED solution is a no-go as it is against the main purpose of having a trusted connection between your front-end and API. We run into this error message recently with a NextJS as the front-end, ExpressJS as the back-end, and Nginx as the webserver.
If you or your team are on implementing the API, I would suggest looking into your webserver config and how you are handling the path of the certificates as the problem might be related to a misconfiguration of the intermediate certificate. Combining the certificate + intermediate certificate like so did the trick for us:
# make command
cat {certificate file} {intermediate certificate file} > {new file}
# config file /etc/nginx/conf.d/xxx.conf
ssl_certificate {new file};
create a next.config.js file if you not already have one in your project and add the following to your webpack config:
const webpack = require("webpack");
module.exports = {
webpack: (config) => {
config.node = {
fs: "empty",
};
process.env.NODE_TLS_REJECT_UNAUTHORIZED = "0";
const env = Object.keys(process.env).reduce((acc, curr) => {
acc[`process.env.${curr}`] = JSON.stringify(process.env[curr]);
return acc;
}, {});
config.plugins.push(new webpack.DefinePlugin(env));
return config;
},
};
Do not use it like this in production. It should only be used in a dev environment.

Gulp-Connect-Php + browserSync + Gulp-Connect address in use issue

I need an ability to use browserSync with php support and some specific url rewrites. I came up with browserSync with Gulp-Connect-Php packages plus Gulp-Connect + modrewrite.
Here is my config:
var
browserSync = require('browser-sync'),
phpconnect = require('gulp-connect-php'),
connect = require('gulp-connect'),
modrewrite = require('connect-modrewrite'),
phpconnect.server({base:'dist/',port: 8010}, function (){
connect.server({
port: 8001,
middleware: function() {
return [
modrewrite([
'^/admin/(.*) - [L]',
'^([^.]*|.*?\.php)$ http://localhost:8010$1 [P,NC]'
])
];
}
})
browserSync({
injectChanges: true,
proxy: '127.0.0.1:8010'
});
})
This works fine and exactly as I need. The following problem occurs from time to time when I launch it:
[error] You tried to start Browsersync twice! To create multiple instances, use browserSync.create().init()
events.js:141
throw er; // Unhandled 'error' event
^
Error: listen EADDRINUSE :::8001
In other words, browserSync starts BEFORE gulp-connect and utilises port 8010 which should be used by gulp-connect and gulp-connect fails to start.
I installed npm sleep package and added the following line before launching browserSync:
sleep.sleep(15)
in other words, I added a 15 seconds delay before launching browserSync.
It works but I bet there is a more elegant solution.
Please, advise.
gulp-connect internally wraps connect, which starts a Node http server.
It emits an event once the server starts called listening. https://nodejs.org/api/net.html#net_event_listening
var
browserSync = require('browser-sync'),
phpconnect = require('gulp-connect-php'),
connect = require('gulp-connect'),
modrewrite = require('connect-modrewrite'),
phpconnect.server({base:'dist/',port: 8010}, function (){
var app = connect.server({
port: 8001,
middleware: function() {
return [
modrewrite([
'^/admin/(.*) - [L]',
'^([^.]*|.*?\.php)$ http://localhost:8010$1 [P,NC]'
])
];
}
})
app.server.on('listening', function () {
browserSync({
injectChanges: true,
proxy: '127.0.0.1:8010'
});
});

Botkit With Express

The documentation at Botkit (https://github.com/howdyai/botkit/blob/master/readme-facebook.md) is pretty not meaningful at all:
// if you are already using Express, you can use your own server instance...
// see "Use BotKit with an Express web server"
controller.setupWebserver(process.env.port,function(err,webserver) {
controller.createWebhookEndpoints(controller.webserver, bot, function() {
console.log('This bot is online!!!');
});
});
Moreover, without a custom webserver (like express), Botkit doesnt provide a way to set the custom local url (instead, it simply chooses 0.0.0.0, which is impractical).
Is anyone successfully assembling app = require('express')(); into the setupWebserver in Botkit (specially for Messenger). If yes, please present the full code.
Hostname for the built in express server can be set when creating your controller:
var controller = Botkit.facebookbot({
hostname: 'YOUR_HOST_NAME',
verify_token: '',
access_token: ''
})
controller.setupWebserver and controller.createWebhookEndpoints are helper functions within botkit to do just what they describe, create an express webserver and webhook endpoints, respectively.
To implement your own webserver, you just need to setup a webhook endpoint for the botkit controller to receive message POST data at and perform auth handshakes.
By botkit convention this is /{platform}/receive so for facebook /facebook/receive but you can use whatever you like.
To use a custom express server with Botkit, first create a basic webserver.
// components/express_webserver.js
var express = require('express');
var bodyParser = require('body-parser');
var querystring = require('querystring');
var debug = require('debug')('botkit:webserver');
module.exports = function(controller, bot) {
var webserver = express();
webserver.use(bodyParser.json());
webserver.use(bodyParser.urlencoded({ extended: true }));
webserver.use(express.static('public'));
// You can pass in whatever hostname you want as the second argument
// of the express listen function, it defaults to 0.0.0.0 aka localhost
webserver.listen(process.env.PORT || 3000, null, function() {
console.log('Express webserver configured and listening at ',
process.env.HOSTNAME || 'http://localhost/' + ':' + process.env.PORT || 3000);
});
// Register our routes, in this case we're just using one route
// for all incoming requests from FB
// We are passing in the webserver we created, and the botkit
// controller into our routes file so we can extend both of them
require('./routes/incoming-webhook')(webserver, controller)
controller.webserver = webserver;
return webserver;
}
Next you need to create the routes for webhook endpoints, we're doing this in a separate file as is common with express
// components/routes/webhook.js
module.exports = function(webserver, controller) {
// Receive post data from fb, this will be the messages you receive
webserver.post('/facebook/receive', function(req, res) {
// respond to FB that the webhook has been received.
res.status(200);
res.send('ok');
var bot = controller.spawn({});
// Now, pass the webhook into be processed
controller.handleWebhookPayload(req, res, bot);
});
// Perform the FB webhook verification handshake with your verify token
webserver.get('/facebook/receive', function(req, res) {
if (req.query['hub.mode'] == 'subscribe') {
if (req.query['hub.verify_token'] == controller.config.verify_token) {
res.send(req.query['hub.challenge']);
} else {
res.send('OK');
}
}
});
}
Once you have created these two files, you will use require and pass your controller into the express module. Your main bot file should look something like this
// bot.js
var Botkit = require('botkit');
// Create the Botkit controller, which controls all instances of the bot.
var controller = Botkit.facebookbot({
debug: true,
verify_token: process.env.verify_token,
access_token: process.env.page_token,
});
// Set up an Express-powered webserver to expose oauth and webhook endpoints
// We are passing the controller object into our express server module
// so we can extend it and process incoming message payloads
var webserver = require(__dirname + '/components/express_webserver.js')(controller);
You can find in github a, MIT-licensed, full Demo of running BotKit for Facebook Messenger on an Express server with MongoDB storage.
Here is the main server.js
// modules =================================================
var express = require('express') // framework d'appli
var app = express()
var bodyParser = require('body-parser') // BodyParser pour POST
var http = require('http').Server(app) // préparer le serveur web
var dotenv = require('dotenv')
var path = require('path')
// configuration ===========================================
// load environment variables,
// either from .env files (development),
// heroku environment in production, etc...
dotenv.load()
app.use(express.static(path.join(__dirname, '/public')))
// parsing
app.use(bodyParser.json()) // for parsing application/json
app.use(bodyParser.urlencoded({ extended: true })) // for parsing url encoded
// view engine ejs
app.set('view engine', 'ejs')
// routes
require('./app/routes/routes')(app)
// port for Heroku
app.set('port', (process.env.PORT || 5000))
// START ===================================================
http.listen(app.get('port'), function () {
console.log('listening on port ' + app.get('port'))
})
okay so here goes i was trying the same thing and have been able to start the botkit up with a custom url on express. You dont have to worry about this code at all:
controller.setupWebserver(process.env.port,function(err,webserver) {
controller.createWebhookEndpoints(controller.webserver, bot, function() {
console.log('This bot is online!!!');
});
});
This repository has its own code with will work with a mongodb database and a express server.
git clone https://github.com/mvaragnat/botkit-messenger-express-demo.git
sudo npm install express --save
sudo npm link body-parser
sudo npm link dotenv
sudo npm install --save botkit
sudo npm install --save monkii
sudo npm install --save mongodb
sudo npm install --save request
sudo npm install --save ejs
In all of the above steps you can perform:
sudo npm link botkit
etc
Finally run node server.js
lt --subdomain botkit --port 5000
restart node server.js
Dont Forget to add your variables to .env file in the directory.
All your traffic on local host will be redirected to the localtunnel, you can get a url using the lt --subdomain name --port 5000
Use this generated url in the webhooks on your page and your bot should be online.

Mixing Wildcards and Parameters in Express

I have web content generated by Minecraft Overviewer in:
/home/mc/backups/servername/latest/overviewer
I have a very simple server with express/nodejs. Here is my app.js:
var express = require('express');
var app = express();
//----------------------------------------------------------------------------+
// Each server's root points to the latest overviewer page |
//----------------------------------------------------------------------------+
app.get('/minecraft/:server/*', function(req, res) {
console.log('HELLO?');
res.send('Finally some luck!');
/*
var
server = req.params.server,
file = req.params[0] ? req.params[0] : 'index.html',
dir = '../backups/' + server + '/latest/overviewer';
res.sendFile(file, { root: dir });
*/
});
app.use(express.static('www'));
app.listen(80, function () {
console.log('Web server listening on port 80');
});
I included a little more code than what is running so you can see my intent in case this is an xy kind of problem. I'm wanting to route static files, but I don't think I can use express.static because I want the URL to be mapped a little differently than my file structure (and based on a server name).
So what's the problem with my simple server? When I try and navigate to mysite.com/minecraft/isopre I see a white page saying Cannot GET /minecraft/isopre. If I remove the * from the end of the string I'm routing on line 7 I see Finally some luck!. But I want the star there so I can map mysite.com/minecraft/isopre to index.html or mysite.com/minecraft/isopre/overviewer.js.
So what's the right way to go about doing this?
In order to perform desirable operation i suggest you to use ? symbol for regular expression:
app.get('/minecraft/:server/:file?', function(req, res, next) {
if('undefined' != typeof req.params.file && req.params.file) {
var file = req.params.file;
}
if('undefined' != typeof req.params.server && req.params.server) {
var server = req.params.server;
}
});
In this case :file become optional and node.js won't fail your entire application if wildcard is absent.
Hereby, if req.params.file variable is undefined you could serve index.html file.

socket.io.js not found (404)

I am referring to an issue that has been asked many times but the solutions posted elsewhere are not resolving my problem ie socket.io.js not found.
The error message is
GET http://127.0.0.1:3000/socket.io/socket.io.js 404
Any help would be appreciated.
I referenced socket.io.js in my JADE file:
script(src='http://code.jquery.com/jquery.js')
script(src='http://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/js/bootstrap.min.js')
script(src='/socket.io/socket.io.js')
script(src='/javascripts/sockets/client.js') // this is in public folder
In my App.js file:
var express = require('express');
io = require('socket.io');
http = require('http');
app = express();
server = http.createServer(app);
io = io.listen(server);
server.listen(app.get('port'), function(){
console.log("Express server listening on port " + app.get('port'));
});
app.use(express.static(path.join(__dirname, 'public')));
These are the versions I am using:
"express": "~4.13.1",
"jade": "~1.11.0",
"morgan": "~1.6.1",
"serve-favicon": "~2.3.0",
"socket.io": "0.9.10"
Some additional info:
In my app.js: I referenced the server socket
// set up our socket server
require('./public/javascripts/sockets/server')(io);
'/javascripts/sockets/client.js' is my client socket:
var socket = io.connect('/');
socket.on('message', function (data) {
data = JSON.parse(data);
$('#messages').append('<div class="'+data.type+'">' + data.message +
'</div>');
});
$(function(){
$('#send').click(function(){
var data = {
message: $('#message').val(),
type:'userMessage'
};
socket.send(JSON.stringify(data));
$('#message').val('');
});
You shouldn't be using the socket.io package for this as it is primarily intended to construct a socket.io server instance. Instead you should be using socket.io-client which was specifically made to be used as the client socket.
I would recommend using bower to install this instead of npm as bower is made for front-end package management. Inside your project directory execute the following
note: If you don't have bower installed you'll need to install it globally npm i -g bower
bower init
bower install --save socket.io-client
Then you should make the bower_components directory created by installing the socket.io-client a static directory
server.use(express.static(path.join(__dirname, 'bower_components')));
Then change
script(src='/javascripts/sockets/client.js') // this is in public folder
to
script(src='/bower_components/socket.io-client)
Additionally, you're mixing your server and app variables. You should be using whatever variable your socket.io was created using, in this case you're using server so you should be using that. Your server file is mostly incorrect as you're instantiating many global values and you've created your io instance incorrectly.
var express = require('express');
var app = express();
var server = require('http').Server(app);
var io = require('socket.io')(server);
var port = process.env.PORT || 3000;
server.use(express.static(path.join(__dirname, 'public')));
server.use(express.static(path.join(__dirname, 'bower_components')));
server.listen(port, function(){
console.log('Express server listening on port ' + port);
});