Getting socket hangup error when using mailchimp api in nodeJs - node.js

i am trying to send a list containing info from a form to mailchimp server,it requires a basic http authentication. When i am sending the request using curl i am able to retrieve the page, but when i run the local sever it is showing socket errors.
const express = require("express");
const bodyParser = require("body-parser");
const request = require("request");
const https = require("https");
const app = express();
app.use(bodyParser.urlencoded({extended:true}));
app.use(express.static("public/"));
app.get("/",function(req,res){
res.sendFile(__dirname+"/signup.html");
});
app.post("/",function(req,res){
console.log(req.body);
const fn = req.body.fn;
const sn = req.body.ln;
const mail = req.body.mailid;
const data ={
members: [
{
email_address: mail,
status: "subscribed",
merge_fields: {
FNAME : fn,
LNAME :sn
}
}
]
};
var url = "https://us4.api.mailchimp.com/3.0/lists/*listid*";
var jsonData = JSON.stringify(data);
var options ={
method: "POST",
auth:"*username*:*key*"
};
const request = https.request(url,options,function(response){
response.on("d",function(d){
console.log(JSON.parse(d));
});
request.write(jsonData);
request.end();
});
});
app.listen(3000,function(){
console.log("at 3000");
});
i am getting the following
error

Try to change
response.on("d",function(d){
console.log(JSON.parse(d));
});
to
response.on("data",function(d){
console.log(JSON.parse(d));
});
and make sure to end the request by specifying request.end();. Otherwise it will not stop posting to the server you have to end posting.

Related

The symbol % becomes %25 when passing it through a Nodejs route

with the following code I bring a report that is hosted on JasperReports Server (This works), the problem is when passing values that have % since it returns %25 in the route and generates an error, any way to solve this problem?
const express = require('express');
const axios = require("axios");
const app = express();
var bodyParser = require("body-parser");
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended:true}))
app.get('/prueba', function(req,res){
res.sendFile(__dirname+"/prueba.html");
});
app.post('/form-submit', async function(req,res){
try {
const url = "http://localhost:8080/jasperserver/rest_v2/reports/reports/Re013.pdf"
const params = {
AMB_OCULTO: req.body.AMB_OCULTO,
AMB : req.body.AMB,
INS : '%',
ORD_INI: req.body.ORD_INI,
ORD_FIN: req.body.ORD_FIN
}
const file = await axios.get(url, {
params: params,
responseType: "stream",
auth:{
username: "jasperadmin",
password: "jasperadmin"
}
})
res.writeHead(200,{"Content-Type":"application/pdf"})
file.data.pipe(res)
} catch (error) {
res.sendFile(__dirname+"/prueba.html");
console.log(error)
}
});

request body is not working - MYSQL and Node JS

I'm trying to create this API with NodeJS, Express and Mysql but when testing on Postman, while the code is working to update the values on the database, it doesn't read the info I insert in the body of the request. For example, I can access the params info (codAluno), but not the request body (Empresa_Atual).
I have two files for the API: routes.js and index.js
const express = require('express')
const bodyParser = require('body-parser')
const app = express()
const db = require('./routes')
const port = 3000
app.use(
bodyParser.urlencoded({
extended: true,
})
)
app.use(bodyParser.json())
app.get('/', (request, response) => {
response.json({ info: 'API' })
})
app.get('/alunos', db.getAlunos)
app.get('/alunos/:id', db.getAlunoByCod)
app.post('/alunos/:id',db.updateAluno)
app.listen(port, () => {
console.log(`App running on port ${port}.`)
})
and routes.js
const mysql = require('mysql');
// Set database connection credentials
const config = {
host: 'localhost',
user: 'user',
password: '',
database: 'student',
};
// Create a MySQL pool
const pool = mysql.createPool(config);
const updateAluno = (request, response) => {
const codAluno = parseInt(request.params.id)
var Empresa_Atual = request.body.Empresa_Atual
pool.query('UPDATE aluno SET `Empresa_Atual`= ? WHERE `codAluno` = ?', [Empresa_Atual, codAluno], (error, result) => {
if (error) throw error;
response.send('User updated successfully.');
});
}
This is the request I'm sending via postman
For example, the variable Empresa_Atual is always null even though I assigned it to the request body.
Can anyone help?
Thanks!
I had the same problem. I had the following: req.params.id. I then changed it to req.params['id'] and it started working. Apparently, the req.params was an object instead of a single value.

twilio API keeps sending request until socket hangs up error occurs

I have been trying to solve this error from a long time. I could not find a similar problem online. I am sending a request through postman to twilio API for whatsapp. Everything seems ok. The promise should send a JSOM object in response but it keeps sending request until socket hangs up error occurs. Here is my code
const dotenv = require('dotenv').config();
const express = require('express');
const { response } = require('express');
const app = express();
app.use(express.json());
exports.sendMessages = function(sender, reciever, message) {
const accountSid = process.env.ACCOUNT_S_ID;
const authToken = process.env.AUTH_TOKEN;
const client = require('twilio')(accountSid, authToken);
client.messages
.create({
from: 'whatsapp:+'+sender,
body: message,
to: 'whatsapp:+'+reciever
})
.then(response => {
return {
data: JSON.stringify(response),
}})
.catch(e => { console.error('Got an error:', e.code, e.message); });
}
Calling the API
const express = require('express');
const app = express();
app.use(express.json());
// for parsing application/json
const send = require('./index');
let endPoint = process.env.ENDPOINT;
app.post(endPoint, function (req, res) {
send.sendMessages('14155238886', '393200149462','test message');
});
const port = process.env.PORT;
app.listen(port);
console.log('Successfully connected to ' +port);

Why my POST request work only with debugger?

I try to write CRUD and checking it up with Postman.
When I use a debugger at the end of the post request it's working.
Problem: When I remove the debugger and try to run the code nothing happens - only error: "Could not get any response". How can I make my post to work well without debugger?
***For example, I send this as JSON through postman like this:
{
"id":3,
"name": "Ron",
"phone": "01323133333"
}
this is the relevant code:
index.js:
const express = require('express');
const app = express();
db = require('./db');
app.use(express.static('public'));
const bodyParser = require('body-parser');
app.use(bodyParser.json());
const port = 1400;
app.listen(port,()=>{
console.log(`Server is running on port ${port}`);
})
//post request:
app.post('/user' , (req,res)=> {
const {body} = req,
{id,name,phone} = body
db.query(`INSERT INTO public.users(
id, name, phone)
VALUES (${id}, '${name}', '${phone}');`,(err,dbRes)=>{
if(err)
res.status(400).send(err);
else
{
res.send(dbRes.rows);
}
})
})
db.js:
const {Client} = require ('pg');
const client = new Client ({
user:'postgres',
host:'localhost',
database:'nodeapp',
password:'123456',
port:5432
})
client.connect();
module.exports = client;
Thank you !

Make voice call using node js

I am using Both Java web server and node js(for chat)
Now I want to make voice call using Twilio`
I wrote code like this
var fs = require('fs');
var sslOptions = {};
var path = require('path');
var express = require('express');
var app = express();
var server = require('https').createServer(sslOptions, app);
const EventEmitter = require('events');
const myEE = new EventEmitter();
server.on("request", function (req, res) {
res.end("this is the response");
});
server.listen('8090', function(){
console.log("Secure Express server listening on port 8090");
});
var accountSid = 'AC***************************';
var authToken = "******************************";
var client = require('twilio')(accountSid, authToken);
var morgan = require('morgan');
var bodyParser = require('body-parser');
var twilio = require('twilio');
var VoiceResponse = twilio.twiml.VoiceResponse;
module.exports = server;
app.use(express.static(path.join(process.cwd(), 'public')));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: true,
}));
app.use(morgan('combined'));
app.get('/', function(request, response) {
response.render('index');
});
app.post('/call', function(request, response) {
var salesNumber = request.body.salesNumber;
var url = 'http://' + request.headers.host + '/outbound/' + encodeURIComponent(salesNumber);
var options = {
to: '+91*******',
from: '+17******',
url: url,
};
client.calls.create(options)
.then((message) => {
response.send({
message: 'Thank you! We will be calling you shortly.',
});
})
.catch((error) => {
console.log('errot');
// console.log(error);
response.status(500).send('error');
});
});
app.post('/outbound/:salesNumber', function(request, response) {
var salesNumber = request.params.salesNumber;
var twimlResponse = new VoiceResponse();
twimlResponse.say('Thanks for contacting our sales department. Our ' +
'next available representative will take your call. ',
{ voice: 'alice' });
twimlResponse.dial(salesNumber);
response.send(twimlResponse.toString());
});
I am trying to make an ajax call from one of my javascript files to an express route
$.ajax({ url: '/call',
method: 'POST',
dataType: 'application/json',
processData: false,
data: {
phoneNumber: '+91*******',
salesNumber:'+17******** '
}
}).done(function(data) {
// The JSON sent back from the server will contain a success message
alert(data.message);
}).fail(function(error) {
//alert('errot');
alert(JSON.stringify(error));
});
when I execute this ajax call
it's looking for Java server and return 404 error
How can I solve this issue
Anyone, please help me to solve this issue

Resources