3

Write simple server as suggested here on stackoverflow:

rest_api.js:

const express = require('express');
const bodyParser = require('body-parser')

// Initialize RESTful server
const app = express();

app.set('port', (process.env.PORT || 5000));
app.use(bodyParser.json() );                        // to support JSON-encoded bodies
app.use(bodyParser.urlencoded({extended: true}));   // to support URL-encoded bodies

// Spin up the server
app.listen(app.get('port'), function() {
    console.log('running on port', app.get('port'))
});

app.post('/bookinghandler', function (req, res) {
    let senderId = req.query.sender;
    let email = req.query.email;
    let hotelName = req.query.hotelName;
    let confirmNumber = req.query.confirmNumber;
    let start = req.query.startDate;
    let end = req.query.endDate;
}

app.js:

// This loads the environment variables from the .env file
require('dotenv-extended').load();

const builder = require('botbuilder');
const restify = require('restify');

// Setup Restify Server
var server = restify.createServer();
server.listen(process.env.port || process.env.PORT || 3978, function () {
   console.log('%s listening to %s', server.name, server.url); 
});

// Create chat connector for communicating with the Bot Framework Service
var connector = new builder.ChatConnector({
    appId: process.env.MICROSOFT_APP_ID,
    appPassword: process.env.MICROSOFT_APP_PASSWORD
});

// Listen for messages from users 
server.post('/api/messages', connector.listen());

var bot = require("./bot")
bot.InitializeBot(connector);

// Load REST API module
var restApi = require("./rest_api");

And want to get parameters through query string (sample request in URL: bookinghandler?sender=100000250242810&email=some@email.com&hotelName=Grand Hotel&confirmNumber=654321&startDate=2017-10-11&endDate=2017-10-15).

However req.params, req.param(), req.body, req.query are still empty. What I'm doing wrong? Is it the only way to do it through require('url') or require('qs')? If I want to it through express only?

Aleksey Kontsevich
  • 4,671
  • 4
  • 46
  • 101

4 Answers4

1

Problem was in using 2 REST frameworks: express and restify. Need to make entire application as restify or express app. Before I had a restify server and inside that another express server was created (just took different examples). Generally need to use one or the other, not both.

Modified app.js:

// This loads the environment variables from the .env file
require('dotenv-extended').load();

const builder = require('botbuilder');
const restify = require('restify');

// Setup Restify Server
var server = restify.createServer();
server.use(require('restify-plugins').queryParser());
server.listen(process.env.port || process.env.PORT || 3978, function () {
   console.log('%s listening to %s', server.name, server.url); 
});

// Index route
server.get('/', function (req, res) {
    res.send('My chat bot')
});

// Create chat connector for communicating with the Bot Framework Service
var connector = new builder.ChatConnector({
    appId: process.env.MICROSOFT_APP_ID,
    appPassword: process.env.MICROSOFT_APP_PASSWORD
});

// Listen for messages from users 
server.post('/api/messages', connector.listen());

var bot = require("./bot")
bot.InitializeBot(connector);

// Load REST API module
var restApi = require("./rest_api");

// POST request from webview page
server.post('/bookinghandler', restApi.BookingHandler);

Modified rest_api.js:

const service = require("./service");

module.exports.BookingHandler = async function (req, res, next) {
    let senderId = req.query.sender;
    let email = req.query.email;
    let hotelName = req.query.hotelName;
    let confirmNumber = req.query.confirmNumber;
    let start = req.query.startDate;
    let end = req.query.endDate;

    res.send(200);  // Success
    return next(false);
};
Aleksey Kontsevich
  • 4,671
  • 4
  • 46
  • 101
0
app.post('/bookinghandler', function (req, res) {
       let senderId = req.query.sender;
       let email = req.query.email;
       let hotelName = req.query.hotelName;
       console.log(req.query, senderId, email, hotelName)
})

Prints this output in my terminal

{ sender: '100000250242810', email: 'some@email.com', hotelName: 'Grand' } '100000250242810' 'some@email.com' 'Grand'

Joe Mayo
  • 7,501
  • 7
  • 41
  • 60
pneedle
  • 9
  • 2
0

I was able to overcome res.query undefined issue by using JSON.parse

const queryValues= JSON.parse(req.query.queriesHere);
console.log(queryValues);
challet
  • 870
  • 9
  • 21
-1

Whenever a request is made with queries, the queries must exist in the url for the server to recognize them.

Here is a sample code for you. You need to add the queries to action in your html form. You also separate them by using &.

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title></title>
  </head>
  <body>
    <form action="/as/?sender=321&email=myemail@email.com" method="post">
      <input type="text" name="myName" value="">
      <input type="submit" name="" value="ssss">
    </form>
  </body>
</html>

Here is app.js

app.post('/bookinghandler', function (req, res) {

    var senderId = req.query.sender;
    var email = req.query.email;
    console.log('senderId = ' + senderId + ' email = ' + email);
    res.end("got the info");
});

Now, you are going to ask me the purpose of this since we are already defining them in the form. Well, real websites don't do it. If you want to evaluate your queries you need to leave them blank and see if the user has any cookies on the browser.

This is the html form

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title></title>
  </head>
  <body>
    <form action="/as/?sender=&email=" method="post">
      <input type="text" name="myName" value="">
      <input type="submit" name="" value="ssss">
    </form>
  </body>
</html>

Here is our app

app.post('/bookinghandler', function (req, res) {
    if(req.session.user.id){  //checking the cookies if the user is logged in/exists
       var senderId = req.query.sender;
       var email = req.query.email;
    }else{
     res.send("you haven't logged in");
     return false;
    }

    console.log('senderId = ' + senderId + ' email = ' + email);
    res.end("got the info");
});

For more info on the node module for cookies please see here

Conclusion

Queries on a form is mostly extra work, the work could be done easily by only using req.body and cookies, req.session objects. People don't usually use it unless they have an extra data to transfer between the client and the server.

UPDATE

Parameters are defined like this /:param in node.js

if you wanna use params

app.get('/bookinghandler/:myParam/?queriesHere='){
   console.log(req.params.myParam + "   and the query: " + req.query.queriesHere);

res.send(req.params.myParam + "   and the query: " + req.query.queriesHere);
}

add this code, and copy and go to this url localhost:5000/bookinghandler/hereisaparam/?queriesHere=123

make sure to add port

if it's a server app, create another node.js file and then run them both

otherfile.js

var request = require('request');
request('http://localhost:5000/bookinghandler/hereisaparam/?queriesHere=123', function (error, response, body) {
  if(error){
console.log(error):
return false;
}
  console.log('body:', body); // Print the data
});

Run this file while the server is running.

Ahmed Can Unbay
  • 2,694
  • 2
  • 16
  • 33