Python socket server not working when deployed - heroku

I'm trying to build a chatbot, but I'm having some issues deploying my server
The program works locally, but when I try to deploy the server in Heroku, I keep receiving, "net::ERR_CONNECTION_TIMED_OUT". I tried everything but I can't find the solution for that.
Client:
<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.3.0/socket.io.js"></script>
<script>
var socket = io("http://bot.herokuapp.com:8080");
function appendHtml(el, str) {
el[0].innerHTML += str;
}
document.getElementsByClassName('input')[0].addEventListener("keyup", function(event) {
if (event.keyCode === 13) {
event.preventDefault();
sendMsg();
}
});
function sendMsg() {
var html = '<div class="message">' + document.getElementsByClassName('input')[0].value + '</div>';
appendHtml(document.getElementsByClassName('messages'), html);
socket.emit("message", document.getElementsByClassName('input')[0].value);
document.getElementsByClassName('input')[0].value = "";
}
socket.on("message", function(data) {
var html = '<div class="message">' + data.response + '</div>';
setTimeout(function(){
appendHtml(document.getElementsByClassName('messages'), html);
}, 1000);
});
</script>
Server:
from aiohttp import web
import socketio
from chatbot.robot import getResponse
# creates a new Async Socket IO Server
sio = socketio.AsyncServer(cors_allowed_origins='*')
# Creates a new Aiohttp Web Application
app = web.Application()
# Binds our Socket.IO server to our Web App
# instance
sio.attach(app)
async def index(request):
with open('index.html') as f:
return web.Response(text=f.read(), content_type='text/html')
#sio.on('message')
async def print_message(sid, message):
await sio.emit('message', {'response': getResponse(message)}, room=sid)
app.router.add_get('/', index)
if __name__ == '__main__':
web.run_app(app)
Heroku commands:
git push heroku master
heroku run python server.py
Heroku logs when I try to connect:
at=error code=H14 desc="No web processes running" method=GET path="/favicon.ico" host=bot.herokuapp.com request_id=... fwd="..." dyno= connect= service= status=503 bytes= protocol=http
My procfile
web: python server.py
After I run the server.py, a message appears saying that the server is running at 0.0.0.0:8080
But I can't connect to the server.

When you run inside Heroku you have to put your web server on the port number indicated in the PORT environment variable. Your code always puts it in 8080.
Try this:
if __name__ == '__main__':
port = int(os.environ.get('PORT', 8080))
web.run_app(app, port=port)

Related

Why am I constantly getting H12 error code AKA 503 status code on Heroku?

Everything works fine while I was in development mode and now when I uploaded my app to heroku I keep getting this error, and the only thing it says is that is a Request timeout.
heroku[router]: at=error code=H12 desc="Request timeout" method=GET path="/visited/posts" dyno=web.1 connect=1ms service=30000ms status=503 bytes=0 protocol=https
But I dont know the reason I get timeout because it was working alright in development.
Might have something to do with the fact that I am on a free dyno?
What I've done so far is to make all the requests in my backed async, but I still get the error. And it happens on several endpoints.
example
const Comment = require('../../models/Comment');
exports.getComments = async (req, res) => {
await Comment
.find({ postId: req.params.postid })
.populate('author')
.exec((error, comments) => {
if (!comments) {
return res.status(404).json({
message: 'No comments found for this post',
});
}
if (error) {
return res.json({ message: error.message, });
}
res.status(200).json({
comments,
});
})
};

Using Koa Routes with Heroku returns 404 errors

I am building my first Shopify public app and used their Next.js and React example to get started. I needed to create an API and couldn't route it with Next.js so I added Koa and Koa-Routes to map it.
It works well locally and I'm able to post and get information from my database using the API. When I deploy it on Heroku, these Koa routes do not work anymore and return 404 errors.
server.js (only the relevant bits)
const Koa = require('koa');
const Router = require('koa-router');
var bodyParser = require('koa-bodyparser');
const next = require('next');
const routes = require('./routes')
const dev = process.env.NODE_ENV !== 'production';
const app = next({ dev });
app.prepare().then(() => {
const server = new Koa();
const router = new Router();
server.use(bodyParser());
server.use(session(server));
server.keys = [SHOPIFY_API_SECRET_KEY];
require('./routes/api')(router);
...
./routes/api
const SettingsControllers = require('../controller/settings');
module.exports = function(router){
router.get('/api/settings/:shop', SettingsControllers.find);
router.put('/api/settings', SettingsControllers.save);
return router
}
Here is the message I get on API calls
heroku[router]: at=info method=GET path="/api/settings/13msdev.myshopify.com" host=app.website.com request_id=12345 fwd="12.12.12.12.12" dyno=web.1 connect=0ms service=3ms status=404 bytes=2020 protocol=https

heroku deployment nodemailer

I can deploy my app locally, but not on heroku. I'm using nodemailer and trying to send mail to myself from my website. This is the route:
app.post('/contact', function (req, res) {
let mailOpts, smtpTrans;
smtpTrans = nodemailer.createTransport({
servic: 'gmail',
auth: {
user: 'randomemail',
pass: 'password'
}
});
mailOpts = {
from: req.body.name + ' <' + req.body.email + '>',
to: 'randomemail',
subject: 'New message from contact form at your portfolio page',
text: `${req.body.name} (${req.body.email}) says: \n \n ${req.body.message}`
};
smtpTrans.sendMail(mailOpts, function (error, response) {
if (error) {
res.render('contact-failure');
}
else {
res.send(response);
}
});
});```
And this is the error I get when I try to send myself mail from heroku.
2018-05-29T06:31:32.280501+00:00 heroku[router]: at=error code=H13 desc="Connection closed without response" method=POST path="/contact" host=desolate-journey-40239.herokuapp.com request_id=4c462f91-9f47-4566-943a-2c5e24d795ac fwd="75.74.137.60" dyno=web.1 connect=0ms service=89ms status=503 bytes=0 protocol=https
NOTE: Some things I've tried going here: https://accounts.google.com/b/0/DisplayUnlockCaptcha and unlocking my account to no avail.
Any response is appreciated. Thanks in advance.
I noticed the typo on 'service' and that seems to have fixed my error.

Parse server cloud code not responding on any query

I recently migrated parseserver to heroku, and everything seems to work perfectly except in my Cloud Code any Parse.Query does not seem to ever respond.
I can run custom cloud code, however anytime I need to run a Parse.Query the request times out.
here is my code:
Parse.Cloud.define("get_remaining_minutes", function(request, response) {
var config_name = "RWMTrialMinutes";
var minutesForPeriod = 120;
var isTrial = true;
var periodStartDate = new Date("01/01/2015");
var minutesUsed = 0;
console.log("userId=" + request.params.userId);
var userQuery = new Parse.Query(Parse.User);
userQuery.get({ useMasterKey: true }).then(request.params.userId, {
success: function(user) {
console.log("success");
response.success(100);
},
error: function(object, error) {
console.log("failed");
response.error(error);
}
});
});
I then call:
curl -X POST -H "X-Parse-Application-Id: xxx" https://xxx.herokuapp.com/parse/functions/get_remaining_minutes?userId=dMbBrRGD1y
and get a timeout
2016-10-13T17:21:21.858269+00:00 heroku[router]: at=info method=POST path="/classes/_User" host=xxx.herokuapp.com request_id=xxx fwd="xxx" dyno=web.1 connect=0ms service=7ms status=404 bytes=225
2016-10-13T17:21:21.788404+00:00 app[web.1]: userId=dMbBrRGD1y
2016-10-13T17:21:51.759088+00:00 heroku[router]: at=error code=H12 desc="Request timeout" method=POST path="/parse/functions/get_remaining_minutes?userId=dMbBrRGD1y" host=xxxx.herokuapp.com request_id=xxx fwd="xxx" dyno=web.1 connect=1ms service=30000ms status=503 bytes=0
I've tried many different ways to query - tried .first, .get, .find, all seem to do the same thing - timeout. If i skip the .get call, the function works fine and I can response.success correctly. However I obviously need to make the query for my code to work.
I feel like i'm missing something basic, like a require or maybe a path is not set up correctly.
I will also mention I am running parse server and dashboard on the same Heroku application if you think that makes a difference as to why the cloud code is failing.
Any ideas?
Edit: adding my index.js code for starting parse-server and dashboard
var express = require('express');
var ParseServer = require('parse-server').ParseServer;
var ParseDashboard = require('parse-dashboard');
var path = require('path');
var allowInsecureHTTP = true;
var databaseUri = process.env.DATABASE_URI || process.env.MONGODB_URI;
var api = new ParseServer({
databaseURI: databaseUri || 'mongodb://localhost:27017/dev',
cloud: process.env.CLOUD_CODE_MAIN || __dirname + '/cloud/main.js',
appId: process.env.APP_ID || 'xxx',
masterKey: process.env.MASTER_KEY || '',
serverURL: process.env.SERVER_URL || 'xxx.herokuapp.com/parse',
restAPIKey: 'xxx',
push:{
ios:{
pfx: 'Push.p12',
bundleId: 'xxx',
production: true
}
}
}, allowInsecureHTTP);
var dashboard = new ParseDashboard({
users: [{
user: 'admin',
pass: 'xxx'
}],
apps: [
{
serverURL: process.env.SERVER_URL + process.env.PARSE_MOUNT || 'https://xxx.herokuapp.com/',
appId: process.env.APP_ID || 'myAppId',
masterKey: process.env.MASTER_KEY || '',
appName: process.env.APP_NAME || 'StoryTime',
iconName: 'Icon-60.png'
}
],
"iconsFolder": "icons"
}, allowInsecureHTTP);
var app = express();
app.use('/public', express.static(path.join(__dirname, '/public')));
var mountPath = process.env.PARSE_MOUNT || '/parse';
app.use(mountPath, api);
//start the dashboard
app.use('/dashboard', dashboard);
app.get('/', function(req, res) {
res.status(200).send('I dream of being a website. Please star the parse- server repo on GitHub!');
});
var port = process.env.PORT || 1337;
var httpServer = require('http').createServer(app);
httpServer.listen(port, function() {
console.log('parse-server-example running on port ' + port + '.');
});
Turns out there were two problems - first the server was configured incorrectly. the SERVER_URL did not have /parse on it - and because the PARSE_MOUNT property was being used to route in express, I missed it. Second the syntax for useMasterKey needs to be like this for .get() - I had copied the code from somewhere online and it was not correct.
userQuery.get(request.params.userId, { useMasterKey:true, success: function(user)....

Why does my react app keep crashing on Heroku?

I don't believe I have any config vars to add...
I added npm start in my package.json.
This is my server.js
var app = express();
var compiler = webpack(config);
app.use(webpackDevMiddleware(compiler, {noInfo: true, publicPath: config.output.publicPath}));
app.use(webpackHotMiddleware(compiler));
app.use(express.static('./dist'));
app.use('/', function (req, res) {
res.sendFile(path.resolve('client/index.html'));
});
var port = 8080;
app.listen(port, function(error) {
if (error) throw error;
console.log("Express server listening on port", port);
});
Heroku Activity Log
2016-06-27T05:26:06.606689+00:00 app[web.1]: > POM#0.3.1 start /app
2016-06-27T05:26:06.970312+00:00 app[web.1]: Express server listening on port 8080
2016-06-27T05:26:12.086607+00:00 app[web.1]: webpack built ece2fe8356b0c26f2ade in 5135ms
2016-06-27T05:26:44.560624+00:00 heroku[router]: at=error code=H20 desc="App boot timeout" method=GET path="/" host=pom1.herokuapp.com request_id=77a8ad82-edc4-4dfb-a624-b1a92a5f008c fwd="173.239.65.34" dyno= connect= service= status=503 bytes=
2016-06-27T05:27:04.972688+00:00 heroku[web.1]: Error R10 (Boot timeout) -> Web process failed to bind to $PORT within 60 seconds of launch
enter code here
It's probably timing out because your app has not connected to the port that heroku provided it. You will be provided with a port number via an environment variable so you should declare your port like this
var port = process.env.PORT || 8080;
That will default to the port specified in the envionment variables (by heroku) and fall back on 8080 if none is set.
I believe the getting started section on heroku touches on this and several other things you should know about deploying to heroku while also providing an example application.

Resources