How to setup a viberbot webhook for heroku deployed nodejs bot? - node.js

I have problem of setting up web hook for my chat bot i made using nodejs. Which is deployed on Heroku.
The app uses the following architecture :
const http = require('http');
const port = process.env.PORT || 8080;
// Viber will push messages sent to this URL. Web server should be internet-facing.
const webhookUrl = process.env.WEBHOOK_URL;
// I have used this as Heroku app name with https://dyno-125-92.herokuapp.com
http.createServer(ot.middleware()).listen(port, () => bot.setWebhook(webhookUrl));
Please, help me to setup a webhook using express or anything that can work with my bot?
I'm stuck.

Try this:
const express = require('express');
const app = express();
// contains relative URL path, like: "/viber/webhook"
const webhookUrl = process.env.WEBHOOK_URL;
// ...
app.use(webhookUrl, bot.middleware());
app.listen(port, () => {
console.log(`Application running on port: ${port}`);
bot.setWebhook(`${process.env.EXPOSE_URL}${webhookUrl}`).catch(error => {
console.log('Can not set webhook on following server. Is it running?');
console.error(error);
process.exit(1);
});
});
If it doesn't work, use - full code example to check.

Related

Socket.io is not connecting on Heroku

I am using Socket.io in my NodeJS backend. However, the sockets do not work. For example, one should receive a link and then send them to all other rooms under the same code, but the code is not executing. In my heroku logs I receive no errors but when I inspect element the page I get
polling-xhr.js:268 GET https://localhost:5000/socket.io/?EIO=3&transport=polling&t=NDADDNH net::ERR_CONNECTION_REFUSED
and
Failed to load resource: net::ERR_CONNECTION_REFUSED
I have looked into similar problems from this forum and made several changes but none of them have solved the issue. Also a bunch of the posts answer with solutions for ws in general which I don't understand at all :/
From what I read the issue might be with my ports? I followed a few of them but the same errors still occured.
Socket.io:
/***BACKEND***/
const express = require('express');
const path = require('path');
const app = express();
let rooms = [];
/***SERVER***/
const port = process.env.PORT || 5000;
server = app.listen(port, function(){
console.log('App is listening on port ' + port)
});
/***SOCKET.IO***/
const socket = require('socket.io');
io = socket(server);
io.on('connection', (socket) => {
//bunch of functionality
}
and then in my client I am using
this.socket = io('localhost:5000');
//one of the functions
this.syncQueue = () => {
this.socket.emit('SYNC_QUEUE', {
activeRoom: this.props.getRoom()
});
}
this.socket.on('RECEIVE_QUEUE', newQueue => {
props.onAddToQueue(newQueue);
});
FYI Everything works on localhost
Localhost will not work on the server and if you are using default namespace you no need to specify the URL. So try this, this.socket = io()
On the client side, you're trying to connect to localhost:5000 instead of the URL Heroku provides. Try this this.socket = io('heroku url goes here').

How to trigger a service in App Engine on Firebase data change

I have created an app engine basic server and connected it for Firebase:
// server.js
// Express packages
const express = require('express');
const app = express();
const path = require(`path`);
const bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({ extended: true }));
// Firebase packages
var firebase = require('firebase');
var firebaseConfig = {...};
var fire = firebase.initializeApp(firebaseConfig);
var ref = firebase.database().ref('test');
ref.on('child_added', readMessage);
function readMessage(data) {
console.log('data', data)
};
// Route index
app.get('/', (req, res) => {
res.send('Hello from App Engine!');
});
// Listen to the App Engine-specified port, or 8080 otherwise
const PORT = process.env.PORT || 8080;
app.listen(PORT, () => {
console.log(`Server listening on port ${PORT}...`);
});
My idea was to trigger this service (not sure which route, but I guess it is open?) when a child is added to the node test on Firebase.
To give a bit of background information, I am basically planning to create a peer connection using webrtc and then parse the video on this nodejs server. I use Firebase for signallin by sending the webrtc information to the node test and then the server can read and process this once there is a change.
I do not understand however how to trigger this service when a child is added (thus when I send some meta data to the node test in Firebase). How do I structure my nodejs code to handle this? Or should this be done differently?
Using cloud function with Firebase Realtime Database triggers, we can call the app engine endpoint using http or Cloud Tasks.

How get response from express server for ajax query in nuxtjs

I'm want to get data from the node/express server after send ajax query from any page of the nuxtjs app.
Usually, for getting and sending ajax query in PHP server, I'm do like this $_GET['var']; echo json_encode('Server got data');
Now I want to use node server express for saving data in mongodb.
When I trying to send a query, response return full code of file test.js.
File index.vue
methods: {
onServer() {
this.$axios.get('/server/test').then(res => {
console.log('res', res.data)
})
}
}
File test.js
var express = require('express');
var app = express();
app.get('*', function (req, res) {
res.send('Hello World!');
});
app.listen(3000, function () {
console.log('Example app listening on port 3000!');
});
File server/index.js
const express = require('express')
const consola = require('consola')
const { Nuxt, Builder } = require('nuxt')
const app = express()
// Import and Set Nuxt.js options
const config = require('../nuxt.config.js')
config.dev = !(process.env.NODE_ENV === 'production')
async function start() {
// Init Nuxt.js
const nuxt = new Nuxt(config)
const { host, port } = nuxt.options.server
// Build only in dev mode
if (config.dev) {
const builder = new Builder(nuxt)
await builder.build()
} else {
await nuxt.ready()
}
// Give nuxt middleware to express
app.use(nuxt.render)
// Listen the server
app.listen(port, host)
consola.ready({
message: `Server listening on http://${host}:${port}`,
badge: true
})
}
start()
I'm a new user node, please help me!
Your main issue is that you are targeting "test.js" in your axios url. This is why it responds with the file rather than what the get route should respond with.
So try with:
this.$axios.get('http://nuxt-profi/server/test').then(...
and see what you get. You should also be able to access that in the browser, just go to your url http://nuxt-profi/server/test and it should show your "Hello World" reponse.
However I can't be sure how you have set all this up. Are you running this as development? In which case maybe you should access it as http://localhost:3000/server/test but maybe you have virtual hosts configured like this. Also, is this a separate backend api or are you trying this as server middleware?
If this doesn't help please give us more info about your project setup and we'll go from there.

Host Actions On Google App With Dialogflow Using Node JS on Self Hosted HTTPS Server (MalformedResponse: Webhook error (206))

I have created one app in actions on google with dialogflow using nodejs. First it is hosted on heroku server, but now i want to host in my server with https.
it works properly on heroku server but not working on my server. It returns error "MalformedResponse: Webhook error (206)"
const express = require('express');
const bodyParser = require('body-parser');
var https = require('https');
var fs = require('fs');
const {
dialogflow,
} = require('actions-on-google');
const app = dialogflow();
const expressApp = express().use(bodyParser.json());
// degault welcome intent on startup
app.intent('Default Welcome Intent', conv => {
conv.ask('Hi, Ask me about Customer Ledger, Outstanding....');
});
app.intent('Default Fallback Intent', conv => {
conv.ask('I didnt understand. Can you tell me something else?');
});
var options = {
key: fs.readFileSync('ssl/office.key'),
cert: fs.readFileSync('ssl/office.crt')
};
var server = https.createServer(options, expressApp).listen(3000, function(){
//express().use(bodyParser.json(), app);
expressApp.post('/fulfillment', app);
console.log("Express server listening on port 3000" );
});
Can anyone suggest me what is the problem with my code?Simulator Screenshot
If you are using express and there is no other layer in between (like Heroku has) to forward requests from port 443 to 3000, the request might not be reaching the target port

Heroku socket.io server runs locally, but not anywhere else

Basically my socket.io server is only working for.. one computer only, I suppose. It works if I use Chrome, Chrome incognito, Edge. I tried using the app with my phone, while on the same Wifi, and that's where I encountered problems. It looked like socket.io just wouldn't work then. I feel like it's only working for one client (maybe ip, port issues?)
I use socket.io in pair with React js, and oh boy it was pain in the arse to make them work both locally and on Heroku.
Here's my server file /src/server/index.js
const express = require("express");
const http = require("http");
const socketIo = require("socket.io");
const axios = require("axios");
const port = process.env.PORT || 4001; // Only this port works for some reason
const index = require("./routes/index");
const app = express();
const path = require('path');
const server = http.createServer(app);
const io = socketIo(server); // < Interesting!
io = socketIo.listen(app);
io.configure(function () {
io.set("transports", ["xhr-polling"]);
io.set("polling duration", 10); // Recommended from online guys
});
app.use(express.static(path.join(__dirname, '../../index')));
app.get('/', (req, res, next) =>
res.sendFile(index))
io.on("connection", socket => {
console.log("New client connected");
})
server.listen(port, () => console.log(`Listening on port ${port}`));
I use config file to dynamically change the server and I import it every time I need to connect to my socket via socket.io-client
let server = 'ws://XXXXXXXXXXXXX.herokuapp.com/socket.io/?EIO=4&transport=websocket';
const env = process.env.NODE_ENV;
if (env === 'development') {
server = 'http://127.0.0.1:4001';
}
module.exports = server;
What could be the problem? Why is only working on my root computer? Could be a dyno problem or something else?
I'm a complete beginner with both heroku and socket.io, so any information would be helpful.
**EDIT:
I am not sure, but I feel like a server running in my VS Code made it work in my heroku app. I have turned it off and the server just keeps sending net::ERR_CONNECTION_REFUSED error.
Solution:
Using mars/heroku-cra-node buildpack is a must. It seperates react-ui and server code. Port config: const port = process.env.PORT || 4001,
Client listens for: let server = window.location.hostname
Also good to have a seperate config file for clientside that has the following:
const env = process.env.NODE_ENV;
if (env === 'development') {
server = 'http://localhost:4001';
}
module.exports = server;
Then you won't have to change ports and servers in development (VSCode) or production (Heroku).

Resources