I use the following code to accept the user sms from my android app and send back the result to the user after making specified get request to some site.the expected output that the user should get is "thanks for your message"+[the response of get request]..what i get is "Thanks for your message undefined"it seems that my variable "body" doesnt get initialized with the GET response.please help
var express = require('express');
var app = express();
app.set('port', (process.env.PORT || 5000));
app.use(express.static(__dirname + '/public'));
app.get('/', function(request, response) {
response.send('Hello Cruel World!');
});
var bodyParser = require('body-parser');
var WEBHOOK_SECRET = "62DZWMCCFFHTTQ44CG3WUQ94CTT7GAAN";
app.post('/telerivet/webhook',
bodyParser.urlencoded({ extended: true }),
function(req, res) {
var secret = req.body.secret;
if (secret !== WEBHOOK_SECRET) {
res.status(403).end();
return;
}
if (req.body.event == 'incoming_message') {
var content = req.body.content;
var from_number = req.body.from_number;
var phone_id = req.body.phone_id;
var request = require("request");
var body;
request("http://www.google.com", function(error, response, data) {
body = data;
});
// do something with the message, e.g. send an autoreply
res.json({
messages: [
{ content: "Thanks for your message! " + body}
]
});
}
res.status(200).end();
}
);
app.listen(app.get('port'), function() {
console.log('Node app is running on port', app.get('port'));
});
please help me to resolve the problem..the answer posted here doesnt seems working http://goo.gl/GYgd6Z,help by taking my code specified here as example...please
The res.json line will execute before the callback from request, so body won't be populated - change like this:
request("http://www.google.com", function(error, response, data) {
// do something with the message, e.g. send an autoreply
res.json({
messages: [
{ content: "Thanks for your message! " + data}
]
});
res.status(200).end();
});
This ensures that the res.json is executed after the response from request().
Related
My code is not working, I can't figure out why and it keeps giving me a 401 meaning the API key is missing so I don't know how this is happening and I would like to figure out what my problem is on this piece of code?
const express = require("express");
const bodyParser = require("body-parser");
const request = require("request");
const app = express();
app.use(express.static("public"));
app.use(bodyParser.urlencoded({extended: true}));
app.get("/", function(req, res){
res.sendFile(__dirname + "/signup.html");
});
app.post("/", function(req, res){
var firstName = req.body.firstName;
var lastName = req.body.lastName;
var email = req.body.email;
var data = {
members: [
{
email_address: email,
status: "subscribed"
}
]
};
var jsonData = JSON.stringify(data);
var options = {
url: "https://us20.api.mailchimp.com/3.0/lists/listId"
method: "POST",
headers: {
"Authorization": "mkouk24 Api Key"
},
body: jsonData
};
request(options, function(error,response,body){
if (error) {
console.log(error);
} else {
console.log(response.statusCode);
}
});
});
app.listen(3000, function() {
console.log("Server is running on port 3000!");
});
First of all, according to the documentation, I think you need to use app.use(bodyParser.json()) in order to pass parameters in post request.
Second, you should generate an API token from MailChimp and add it here Authorization": "mkouk24 Api Key"
More on that on this link: https://mailchimp.com/help/about-api-keys/
So i am using ionic framwork to make my app and using nodeJS as my backend but i am still a noob in this and i can't seem to figure it out still after 4 days so hopefully someone could answer this problem to me and why would be appreciated.
So for my ionic client side i do this to make a http.post request
progress() {
var headers = new HttpHeaders();
headers.append('Accept', 'application/json');
headers.append('Content-Type', 'application/json');
let options = {headers: headers};
let postData = {
username: this.username,
email: this.email,
password1: this.password1,
password2: this.password2
};
this.http.post('localhost:4000/api/users', postData, options,).subscribe(
data => {
console.log(data);
},
error => {
console.log(error);
});
}
and this is what i am doing to get the data from the server but that's not working
// Packages
let express = require('express');
var request = require('request');
var bodyParser = require('body-parser');
var cors = require('cors');
const app = express();
app.use(cors({origin: 'http://localhost:8100'}));
const port = 4000;
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
// Whenever you enter localhost:4000/ //
app.get('/', function (req, res) {
res.send(('Server runs'));
});
app.listen(port, () => console.log(`app listening on port ${port}!`));
app.get('/api/users', (req, res) => {
res.send('api/users page');
request.get({
uri: 'http://localhost:8100/create-account'
}, function (err, res, body) {
console.log('error:', err); // Print the error if one occurred and handle it
console.log('statusCode:', res && res.statusCode); // Print the response status code if a response was received
res.send(body);
});
});
i also tried 'http://localhost:8100' & 'localhost:8100'
so someone help me
You need to add a handler for your POST request. To do this use app.post, and it looks like this
app.post('/api/users', (req, res) => {
// You can find your data here
const data = req.body;
console.log(data);
// Send back a response
res.sendStatus(200);
});
I am trying to call a REST API from node using node-rest-client. In the event that my call returns an error, I want to catch the error and report it to the caller.
I am trying this with Postman, unfortunately this only works once. When I press send the second time, my node.js program crashes with the error "Can't set headers after they are sent."
I am new at node.js, so any help is highly appreciated!
//app stuff
const client_id = "x";
const client_secret = "y";
const callback = "https://myurl;
// Basic Setup
var http = require('http'),
express = require('express'),
mysql = require('mysql'),
parser = require('body-parser'),
Client = require('node-rest-client').Client;
var client = new Client();
// Setup express
var app = express();
app.use(parser.json());
app.use(parser.urlencoded({ extended: true }));
app.set('port', process.env.PORT || 5000);
// Set default route
app.get('/', function (req, res) {
res.send('<html><body><p>Welcome to Bank API Wrapper</p></body></html>');
});
app.post('/authorize', function (req,res) {
var response = [];
if (typeof req.body.code !== 'undefined' && typeof req.body.state !== 'undefined' ){
var code = req.body.code, state = req.body.state;
//conversion to base64 because citi api wants it this way
var authorization = "Basic " + Buffer.from(client_id + ":" + client_secret).toString('base64');
var args = {
data:{"grant_type":"authorization_code","code":code,"redirect_uri":callback},
headers:{"Authorization":authorization,"Content-Type":"application/x-www-form-urlencoded"}
};
//get access and refresh token
client.post("https://sandbox.apihub.citi.com/gcb/api/authCode/oauth2/token/sg/gcb", args, function (citidata, citiresponse) {
//console.log(citidata);
//console.log(citiresponse);
});
client.on('error', function (err) {
response.push({'result' : 'error', 'msg' : 'unauthorized access'});
res.setHeader('Content-Type', 'application/json');
res.status(200).send(JSON.stringify(response));
});
}
else {
response.push({'result' : 'error', 'msg' : 'Please fill required details'});
res.setHeader('Content-Type', 'application/json');
res.status(200).send(JSON.stringify(response));
}
});
// Create server
http.createServer(app).listen(app.get('port'), function(){
console.log('Server listening on port ' + app.get('port'));
});
You've got this:
client.on('error', function (err) {
This register an error handler on the client but it never gets removed. The client is shared between requests so any errors on subsequent requests will still fire the old error handlers.
Instead you can listen for an error on the request. Something like this:
var request = client.post("...
request.on('error', function(err) {
// handle error
});
See https://www.npmjs.com/package/node-rest-client#error-handling
I am writing a program which will send a mail on clicking a button in html using nodemailer.
My Application server is running on 8383 port and the node server is running on 8080.
I am getting an error "POST http://127.0.0.1:8080/Webcontent/api/mail 404 (Not Found) 127.0.0.1:8080/Webcontent/api/mail:1
Error: Cannot POST /Webcontent/api/mail"
Kindly look into the code and suggest a solution.
server.js file
var express = require('express'),
cors = require('cors');
var app = express();
app.use(cors());
var port = process.env.PORT || 8080;
var database = require('./config/database');
var morgan = require('morgan');
var bodyParser = require('body-parser');
var methodOverride = require('method-override');
app.use(express.static(__dirname + '/public'));
app.use(morgan());
app.use(bodyParser.urlencoded({'extended':'true'}));
app.use(bodyParser.json());
app.use(bodyParser.json({ type: 'application/vnd.api+json' }));
app.use(methodOverride('X-HTTP-Method-Override'));
require('./app/routes.js')(app);
app.listen(port);
console.log("App listening on port " + port);
routes.js file
var User = require('./models/user');
var Mail = require('./models/mail');
module.exports = function(app) {
app.post('http://127.0.0.1:8080/Webcontent/api/mail ', function(req, res) {
console.log('inside post');
Mail.fire(req.body.text1);
console.log(req.body.text1);
});
app.get('*', function(req, res) {
console.log('fff');
res.sendFile('index.html', { root: path.join(__dirname, './public') });
});
};
mail.js file
var nodemailer = require("nodemailer");
var smtpTransport = nodemailer.createTransport("SMTP",{
service: "Gmail", // sets automatically host, port and connection security settings
auth: {
user: "test#gmail.com",
pass: "Test"
}
});
exports.fire= function fire(username){
smtpTransport.sendMail({ //email options
from: "test#gmail.com", // sender address. Must be the same as authenticated user if using GMail.
to: "receive#yahoo.com", // receiver
subject: "mail using nodemailer", // subject
text: "mail body text" // body
}, function(error, response){ //callback
if(error){
console.log(error);
}else{
console.log("Message sent: " + response.message);
}
smtpTransport.close(); // shut down the connection pool, no more messages. Comment this line out to continue sending emails.
});
};
controller.js file// used to call the function(sendmail) on button click
$scope.sendMail = function() {
//alert("inside createtodo");
$http.post('http://127.0.0.1:8080/Webcontent/api/mail', $scope.formData).success(function(data) {
//alert("inside success");
$scope.formData = {};
$scope.users = data;
//console.log(data);
})
.error(function(data) {
//alert("Bad Luck....");
console.log('Error: ' + data);
});
};
Just change in your route.js file:
app.post('/Webcontent/api/mail', function(req, res) {
console.log('inside post');
Mail.fire(req.body.text1);
console.log(req.body.text1);
});
How do I get the caller ID from twilio? I've tried many different ways to get the POST data but it isn't working.
var twilio = require('./node_modules/twilio/index'),
http = require('http'),
express = require('express');
http.createServer(function (req, res) {
/*
var app = express();
app.use(express.urlencoded());
app.post('/call',function (req, res) {
*/
var name, from;
// if (req.method=='POST')
// req.on('From', function (data) {from = data;});
try {
from = req.param('From');
// from = req.body.from;
}
catch (err)
{
console.log("No Caller ID");
}
console.log("Number: " + from);
//Some code goes here..
res.end(resp.toString());
}).listen(8080);
It's throwing me the error every single time at the try catch statement (always null).
I'm trying to get the caller ID of an incoming text message.
Things in comments are the different approaches I tried.
The thrown error is:
Error TypeError: Object #IncomingMessage> has no method 'param'
I guess that this will do the trick:
var qs = require('querystring');
var processRequest = function(req, callback) {
var body = '';
req.on('data', function (data) {
body += data;
});
req.on('end', function () {
callback(qs.parse(body));
});
}
var http = require('http');
http.createServer(function (req, res) {
processRequest(req, function(data) {
// data
});
}).listen(9000, "127.0.0.1");