Error in connect econnrefused response from server - node.js

I got the error from the server with errorno: ECONNREFUSED
My API is working perfectly on my local machine. When I host the code I got a connection error.
If you hit the URL direct you'll get products http://nodenpm.club:3001/products
Here is the API URL which i'm using for accessing the order with products http://nodenpm.club:3002/orders
but when i access this URL using request i got below error
{
"status": false,
"error": {
"errno": "ECONNREFUSED",
"code": "ECONNREFUSED",
"syscall": "connect",
"address": "172.17.0.3",
"port": 3001
}
}
I am using the Ubuntu server for hosting with docker. I have also tried with proxy request but does not work. below is my code for request.
const express = require("express");
const request = require('request');
const app = express();
app.get("/orders", (req, res) => {
var options = {
url: 'http://nodenpm.club:3001/products',
headers: { 'Content-Type': 'application/json' }
};
request(options, (error, response, body) => {
if (!error) {
res.status(200).json({
status: true,
body: body
});
}
})
});
app.listen(3002, () => {
console.log('order services listening on http://nodenpm.club:3002');
});
my expceted output is below
{
"status": true,
"products": [
{
"_id": "5d5f84afdb78bd0b10e38879",
"name": "mobile",
"price": 10000
}
]
}

i think You have to put the URL into an object for example:
{url:"http://nodenpm.club:3001/products"}

You don't include the method of the request. Try:
request.get(options, (error, response, body) => {
if (!error) {
res.status(200).json({
status: true,
body: body
});
}
})

Related

Node js if status of http post request is 401 then execute another post request

I have the below https post request, which is very simple. The code works as expected when using an active token. when using an expired token it receives a 401 error. This is ok. I would like to run a diiferent post request if i receive a 401.
what code can I add to make it check for 401 status and run a different post request? I'm new to node js. Should I use a function? promise?
const https = require('https');
const postData = JSON.stringify({
"data": [
{
"Company": "Test Company",
"Last_Name": "test",
"First_Name": "test",
"Email": "test#gmail.com",
}
],
"trigger": [
"test"
]
});
const options = {
method: 'POST',
hostname: 'www.host.com',
path: '/crm/xxx',
headers: {
'Authorization': 'oauthtoken 1000.xxxxxxxxxxxxx',
'Content-Type': 'application/json',
'Content-Length': postData.length
}
};
const req = https.request(options, (res) => {
console.log('Status Code:', res.statusCode);
if (res.statusCode == '401'){
// run other post request here? somewhere else?
console.log('rec 401 status code');
}else{
console.log('did not rec 401');
}
}).on("error", (err) => {
console.log("Error: ", err.message);
});
req.write(postData);
req.end();

How to send webhook to jotForm from my site?

I'm working to send the data from my server to the webhook.
I'm using a "REQUEST" service, but I'm getting an error. My request hits there but I'm getting an error.
var request = require('request');
var data:any = [];
data[5] = {email5 : "abc#gmail.com"};
request.post({
"url": "https://api.jotform.com/form/formId/submissions?apiKey=apikey",
"json": {
submission : data
},
"headers": {
"Content-type": "application/json"
}
}, (error:any, response:any) => {
if (error) {
console.log(error);
}
else {
if(response){
console.log(response);
console.log('=================');
}
}
});
I'm getting an error of questionId.
Here is my error
body:
{ responseCode: 500,
message: 'error',
content: 'QuestionID not found on form questions!',
duration: '29ms' } }
Please help me!

Error: Can't set headers after they are sent Ember/Nodejs

I am trying to fetch data from an API, if you see the console ,you will find that a huge chunk of JSON that is variable a2 is displayed in the console .
But I wish to do res.json(a2); to display all the json on the webpage as JSON data.
I am getting an error--
Error: Can't set headers after they are sent.
What do I do >
var express = require('express');
var app = express();
const port = 5000;
var gotit = [];
var Request = require("request");
Request.post({
"headers": {
"content-type": "application/json",
"Authorization": "34ca0e9b-ecdd-4736-a432-d87760ae0926"
},
"url": "https://www.lifeguard.insure/v1/quote",
"body": JSON.stringify({
"category": "Auto",
"zipcode": "90293",
"age": 35,
"gender": "Male",
"key": "a2bf34ab-8509-4aa6-aa9e-13ae7917e1b8"
})
}, (error, response, body) => {
if (error) {
return console.dir(error);
}
var a2 = (JSON.parse(body));
console.log(a2)
gotit = a2;
});
console.log("Gotiit")
console.log(gotit);
app.get('/api/customers', (req, res) => {
res.json(gotit);
});
app.listen(port, () => console.log("Server Started"));
It looks like your making that request when your server boots?
maybe it'll work if the request is made inside the route handler?
like,
app.get('/api/customers', (req, res) => {
var gotit = [];
// all that request code, but in here
res.json(gotit);
});

Facebook Messenger Bot : Socket hang up exception while sending message back to user using nodejs?

I have taken a example fb mot from git set up the node js app and subscribed to webhooks.
Below is the code :
'use strict';
const express = require('express')
const bodyParser = require('body-parser')
const request = require('request')
const app = express()
const fs = require('fs')
const https = require('https')
app.set('port', (process.env.PORT || 5000))
// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({extended: false}))
// parse application/json
app.use(bodyParser.json())
// index
app.get('/', function (req, res) {
res.send('hello world i am a secret bot')
})
// for facebook verification
app.get('/webhook/', function (req, res) {
if (req.query['hub.verify_token'] === 'my_voice_is_my_password_verify_me') {
res.send(req.query['hub.challenge'])
console.log("verified");
} else {
res.send('Error, wrong token')
}
})
// to post data
app.post('/webhook/', function (req, res) {
let messaging_events = req.body.entry[0].messaging
for (let i = 0; i < messaging_events.length; i++) {
let event = req.body.entry[0].messaging[i]
let sender = event.sender.id
if (event.message && event.message.text) {
let text = event.message.text
if (text === 'Generic'){
console.log("welcome to chatbot")
//sendGenericMessage(sender)
continue
}
sendTextMessage(sender, "Text received, echo: " + text.substring(0, 200))
}
if (event.postback) {
let text = JSON.stringify(event.postback)
sendTextMessage(sender, "Postback received: "+text.substring(0, 200), token)
continue
}
}
res.send(200)
})
// recommended to inject access tokens as environmental variables, e.g.
// const token = process.env.FB_PAGE_ACCESS_TOKEN
const token = "<TOKEN>"
function sendTextMessage(sender, text) {
let messageData = { text:text }
request({
url: 'https://graph.facebook.com/v2.6/me/messages',
qs: {access_token:token},
method: 'POST',
json: {
recipient: {id:sender},
message: messageData,
}
}, function(error, response, body) {
if (error) {
console.log('Error sending messages: ', error)
} else if (response.body.error) {
console.log('Error: ', response.body.error)
}
})
}
function sendGenericMessage(sender) {
let messageData = {
"attachment": {
"type": "template",
"payload": {
"template_type": "generic",
"elements": [{
"title": "First card",
"subtitle": "Element #1 of an hscroll",
"image_url": "http://messengerdemo.parseapp.com/img/rift.png",
"buttons": [{
"type": "web_url",
"url": "https://www.messenger.com",
"title": "web url"
}, {
"type": "postback",
"title": "Postback",
"payload": "Payload for first element in a generic bubble",
}],
}, {
"title": "Second card",
"subtitle": "Element #2 of an hscroll",
"image_url": "http://messengerdemo.parseapp.com/img/gearvr.png",
"buttons": [{
"type": "postback",
"title": "Postback",
"payload": "Payload for second element in a generic bubble",
}],
}]
}
}
}
request({
url: 'https://graph.facebook.com/v2.6/me/messages',
qs: {access_token:token},
method: 'POST',
json: {
recipient: {id:sender},
message: messageData,
}
}, function(error, response, body) {
if (error) {
console.log('Error sending messages: ', error)
} else if (response.body.error) {
console.log('Error: ', response.body.error)
}
})
}
// Start server
// Webhooks must be available via SSL with a certificate signed by a valid
// certificate authority.
https.createServer({
}, app).listen(app.get('port'), function() {
console.log("Hello World.This is Airbot :)");
});
module.exports = app;
Link to github project : https://github.com/jw84/messenger-bot-tutorial
I am not not able to send the messages back to the user.
Getting the following error :
Error sending messages: { Error: socket hang up
at TLSSocket.onHangUp (_tls_wrap.js:1124:19)
at TLSSocket.g (events.js:291:16)
at emitNone (events.js:91:20)
at TLSSocket.emit (events.js:185:7)
at endReadableNT (_stream_readable.js:974:12)
at _combinedTickCallback (internal/process/next_tick.js:80:11)
at process._tickDomainCallback (internal/process/next_tick.js:128:9) code: 'ECONNRESET' }
Appreciate help!

Can send post request with curl but cannot from a node server

I can make a post request to a REST api endpoint of a web service with curl successfully but couldnt do so with request module in node.js. Instead, I always get error CONNECTION ETIMEDOUT.What is the problem?
curl command:
curl -i --header "Content-Type: application/json" -XPOST 'http://<endpoint_url>/urls' -d '{
"callback": "http://www.example.com/callback",
"total": 3,
"urls": [ {
"url": "http://www.domain.com/index1.html"
}, {
"url": "http://www.domain.com/index2.html"
}, {
"url": "http://www.domain.com/index3.html"
}
]
}'
code:
function sendRequestToEndPoint() {
const sample = {
"callback": "http://www.example.com/callback",
"total": 3,
"urls": [ {
"url": "http://www.domain.com/index1.html"
}, {
"url": "http://www.domain.com/index2.html"
}, {
"url": "http://www.domain.com/index3.html"
}
]
}
const options = {
method: 'post',
//headers: {
// 'Content-Type': 'application/json',
// 'Accept': 'application/json',
//},
url: 'http://<endpoint_url>/urls',
json: sample
//body: JSON.stringify(sample) // also tried this with headers on
};
console.log(sample);
request(options, (error, response, body) => {
console.log(response)
});
}
Update: Turned out that it was because the api url I used is not correct.
use querystring to stringify your json data,
var querystring = require('querystring');
...
sample = querystring.stringify(sample);
look at this answer How to make an HTTP POST request in node.js
this code works,
you need to Stringify your json object using JSON.stringify , and use the methode write of the object request to send the sample json object
, http = require('http')
, bodyParser = require('body-parser');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: false
}));
var sample = JSON.stringify({
"callback": "http://www.example.com/callback"
, "total": 3
, "urls": [{
"url": "http://www.domain.com/index1.html"
}, {
"url": "http://www.domain.com/index2.html"
}, {
"url": "http://www.domain.com/index3.html"
}
]
});
var options = {
hostname: 'localhost'
, port: 80
, path: '/test/a'
, method: 'POST'
, headers: {
'Content-Type': 'application/json'
, 'Content-Length': sample.length
}
};
app.get('/', function (req, res) {
var r = http.request(options, (response) => {
console.log(`STATUS: ${response.statusCode}`);
console.log(`HEADERS: ${JSON.stringify(response.headers)}`);
response.setEncoding('utf8');
response.on('data', (chunk) => {
console.log(`BODY: ${chunk}`);
});
response.on('end', () => {
console.log('No more data in response.');
});
});
r.on('error', (e) => {
console.log(`problem with request: ${e.message}`);
});
r.write(sample);
r.end();
res.send('ok');
});
a link for more details about http.request nodejs.org http.request(options[, callback])

Resources