getting a parameter from a callback request using node.js and express - javascript

I'm using the twilio API and node.js to successfully record and transcribe calls. I'm trying to implement a callback when a call is recorded. According to the twilio API, I specify my callback URL:
twiml.record({
transcribe: false,
maxLength: 30, //seconds to record
recordingStatusCallback: 'http://[url]:3000/recorded'
})
Per the documentation, I should receive some parameters back via POST, so I am logging the request and response:
app.post('/recorded', (req, res) => {
console.log(req, res)
})
What I get back in the log is a couple of giant objects, and I don't see anything that looks like the parameters I'm expecting. I'm guessing I'm supposed to be constructing that post function differently to get the parameters I need, but i'm not sure how, and I don't see any documentation in Twilio or online that shows how a successful callback function is structured.
Any ideas how to do this?

First of all add 'body-parser' module to your project.
npm install body-parser
And require it in the code:
var bodyParser = require('body-parser')
Now add it somewhere in the code before launching the server:
app.use(bodyParser.urlencoded({ extended: false })); //this will add extracting of the body for every request to express server
After that, in your functions, where you are trying to find data, you can get it using such code:
app.post('/recorded', (req, res) => {
console.log(req.body); //body of the request in javascript object format
})
Find more info about 'body-parser' module here.

Related

What's the NodeJS / Express equivalent to PHP's file_get_contents('php://input')?

In PHP I can fetch incoming JSON from let's say an AJAX request by calling file_get_contents('php://input'), I'm now rebuilding my API in NodeJS (TypeScript) and am looking for an equivalent to fetch incoming JSON.
Various web searches did not deliver what I was looing for, so I hope to find help here.
You can try to call the correct URL by using Axios. Following this link https://www.npmjs.com/package/axios for more.
You can use bodyparser for express and receive data via post.
let app = express();
const bodyParser = require("body-parser");
app.listen(port);
console.log('API started port' + port);
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.post('/path', "maybe cors()", function(req, res){
let data = req.body.data //data is the json you get
}
Thats the way i fetch json that gets send to the server. Hope you can make something with it.

Nodejs + Express: How to get an element which made an HTTP GET request?

I am making a front using Express. I have a table where each row has a link that makes a GET request, so that the back-end (done with node.js) returns a file corresponding to that row.
All links make the url GET request like "/documents/table/file".
What I intend to do is for my express server to be able to know which link of what row makes the GET request with the req field of it in order to be able to return the corresponding requested file.
The request is being handled in my express server as follows:
router.get('/documents/table/file', async (req, res) =>{
//Get which element made the get petition
});
As I said before, I intend to know what link from which row of the table performs a request using the req field.
You need to pass the information about the row/item that makes the GET request, that is a must.
Now with Express there are a couple of ways to do this: Express routing.
1. Defining route params: req.params
GET Request: /documents/table/file/345 (345 is the row identifier name or id etc)
At nodejs express end:
router.get("/documents/table/file/:id", (req, res) => {
/*request parameter with this kind of route sits in req.params*/
console.log(req.params);
const requestedId = req.params.id;
});
2. Sending as query string parameters: req.query
GET Request: /documents/table/file?id=345
At nodejs express end:
router.get("/documents/table/file/", (req, res) => {
/*request parameter with this kind of route sits in req.query*/
console.log(req.query);
const requestedId = req.query.id;
});
The short version is: you can't know this.
The way this is normally handled that if a request is needed for a specific item (or row in a table), you need to add some relevant information to the url that can identify it yourself.
So if it's a GET request for /foo/get-file, and every 'file' has some kind of unique id, you might want to change your url to /foo/get-file/123 or /foo/get-file?id=123
Do you want to access specific file using get command? If so, here's an answer - Express router - :id?.
More precisely, you write something like router.get('/documents/table/file/:id), and this :id is available in req.params object.

node.js internal message server

I am pretty new to node.js. I am working on an app able to display NFC content on a webpage. I am using nfc-pcsp package (https://github.com/pokusew/nfc-pcsc), I can easily read data on server side. Now I just would like to display the data in the webpage, but I am stuck on the logic. Here is a part of my server code:
// ### launch server for client
var http = require('http');
var html = require('fs').readFileSync(__dirname+'/custom.html');
var server = require('http').createServer(function(req, res){
res.end(html);
});
server.listen(3000, '127.0.0.1');
console.log('Server running at http://127.0.0.1:3000/');
//######
//#launch NFC routine ######
const nfc = new NFC(); // const nfc = new NFC(minilogger); // optionally you can pass logger to see internal debug logs
let readers = [];
nfc.on('reader', async reader => {
pretty.info(`device attached`, { reader: reader.name });
// the event is correctly displayed in the console. How to update html here?
readers.push(reader);
nfc.on('error', err => {
pretty.error(`an error occurred`, err);
});
It seems to me that I need a res object to update the html page, but as I do not get any request from client, how do I update the page just based on the callback from NFC module reader? Hope my question is clear.
Thanks,
Matt
I suggest you to use the express API
command with npm CLI : npm install --save express at your root project folder in your terminal
Then, you will be able to create a route in Get, Post, Put or Delete.
Next, In your client side you will be able to call this route by a get, post or whatever with a promise, ajax request whatever you want :)
Just understand that in order to receive or send data to your server, you need an url and with Express, you can create your own url.
https://www.npmjs.com/package/express
Don't hesitate to have a look on this API, and i'm pretty sure you will find the answer to your question on your own :)

Attempting to send object from client to server (AngularJS $http.post)

I'm attempting to store an object that my user clicks on in my server so that when the page changes, all the information from that object can be displayed fully in a profile page.
I'm unfamiliar with Angular $http but I've tried to write a call that will POST to the server, unfortunately when I scan through the req object in VScode I can't find where the object I sent is contained, so I can send it on to my function.
Controller function:
$scope.storeProfile = function(child){
$http.post('/storeTempProfile', child)
.then(function(response) {
window.location.href = 'DemoPage.html';
});
}
server.js:
app.post('/storeTempProfile', function (req, res) {
profileStorage.storeProfile(req);
});
does my app.post look right? And what property of req do I need to use the dot operator on to access my object? I can't seem to find the object data anywhere in req and that makes me thing there's something wrong with how I wrote app.post
It looks like you are using express. So in that case, you want to access the object on req.body, but this will require you use body-parser. The example on their homepage:
var express = require('express')
var bodyParser = require('body-parser')
var app = express()
// create application/json parser
var jsonParser = bodyParser.json()
// POST /api/users gets JSON bodies
app.post('/api/users', jsonParser, function (req, res) {
if (!req.body) return res.sendStatus(400)
// create user in req.body
})
You will notice in this example that they pass the json parser into the route itself. This is only necessary if you want to have different parsers for different routes. Usually you just want to set it to all routes, which you can do by using app.use(bodyParser.json()).

Node JS app only display the first JSON object. Why?

I am trying to write a json object in my node application, integrating the Twilio API. When console logging the object all objects are returned properly but when I write it to the document only the first object is written. Why? How should I change the code to see the same written response as in my console log.
var express = require('express');
var app = express();
app.use(express.bodyParser());
app.get('/', function(req, res) {
var accountSid = 'xxx';
var authToken = 'xxx';
var client = require('twilio')(accountSid, authToken);
client.messages.list({
from: "xxx",
to: "xxx"
}, function(err, data) {
data.messages.forEach(function(message) {
console.log(message.body); // THIS WILL DISPLAY ALL OBJECTS
res.json(message.body); // THIS WILL ONLY DISPLAY THE FIRST OBJECT
});
});
});
app.listen(1337);
I am new to Node JS and think this is easy to solve, but I still can’t find the solution.
res.json(...); sends back the response. You are doing that in the first iteration over the array, hence the client only gets the first message.
If you want to extract body from all messages and send all of them back, then do that. Create an array with the data you want and send it back. Example:
res.json(data.messages.map(function(message) {
return message.body;
}));
You can only call res.json once per request. You're calling it multiple times in a loop. The first time you call it, the browser receives the response, and you'll get a headers already sent exceptions (or something like that) for all other res.json calls.
res.json actually does a data conversion to JSON. I'd be willing to bet there is something it is not dealing with, or it's simply screwing it up. If the response from Twilio is already json, you probably don't need to do that. Try res.send, instead, which just returns whatever you got back.

Categories