I'm trying to send http post request using native node js http request.
I'm using the following code but nothing happens:
var http = require('http');
var options = {
hostname: '192.168.1.134',
port: '8082',
path: '/api',
method: 'POST',
headers: {'content-type': 'application/json',
'cache-control': 'no-cache'}
};
callback = function(response)
{
var result = [];
response.on('data', function (chunk)
{
result.push(chunk);
});
response.on('end', function ()
{
console.log("LOCAL END" + result);
});
}
var req = http.request(options, callback);
req.write(JSON.stringify(
{
customer: 'customer',
deviceIndicator: 'id',
userId: 'id2',
lastVersion: 999
}), 'utf8' ,
function(data)
{
console.log('flushed: ' + data);
});
req.end();
console.log(" - trying to post to example - done" );
But if i'm adding the following dummy calls i'm getting an answer from my local server as expected:
var options1 = {
hostname: 'www.google.com',
port: '80',
path: '/',
headers: {'cache-control': 'no-cache'}
};
callback1 = function(response1) {
var str = ''
response1.on('data', function (chunk) {
str += chunk;
});
response1.on('end', function () {
console.log("GOOGLE END" + str);
});
}
var req1 = http.request(options1, callback1);
req1.end();
console.log("sent to google - done");
What am i doing wrong?
Make sure 192.168.1.134:8082 is reachable and responding (using a browser, curl or wget) then try adding a content-length header:
var http = require('http');
var payload = JSON.stringify({
customer: 'customer',
deviceIndicator: 'id',
userId: 'id2',
lastVersion: 999
});
var options = {
hostname: '192.168.1.134',
port: 8082,
path: '/api',
method: 'POST',
headers: {
'content-length': Buffer.byteLength(payload), // <== here
'content-type': 'application/json',
'cache-control': 'no-cache'
}
};
var req = http.request(options, function(response) {
var result = [];
response.on('data', function(chunk) {
result.push(chunk);
});
response.on('end', function () {
console.log('LOCAL END' + result);
});
});
req.write(payload);
req.end();
Eventually, I discovered that the problem was with the device itself which had some kind of problem..
When sent http request to a direct ip address nothing happened but when sent to an address that need dns server it is working...
Unfortunately, I don't have any additional info about this bug...
Related
I am trying to call a STRIPE api from the Node JS https module, after the control reaching the below line, req.end() is executed and exited the function, I couldn't see any error, result or anything.. Not sure where am i going wrong
Please find the complete snippet, I need to do some operation after the success or error response from the https.request call
const https = require('https');
var fs = require('fs');
var qs = require('querystring');
var postData = qs.stringify({
'amount': '2000',
'currency': 'usd',
'source': 'tok_visa',
'description': 'pizza order'
});
var options = {
'method': 'POST',
'host': 'api.stripe.com',
'path': '/v1/charges',
'headers': {
'Authorization': 'Bearer sk_test_4eC39HqLyjWDarjtT1zdp7dc',
'Content-Type': 'application/x-www-form-urlencoded',
'content-length': Buffer.byteLength(postData)
},
'maxRedirects': 20
};
var req = https.request(options, function (res) {
var chunks = [];
res.on("data", function (chunk) {
chunks.push(chunk);
});
res.on("end", function (chunk) {
var body = Buffer.concat(chunks);
callback(body);
});
res.on("error", function (error) {
callback(error);
console.error(error);
});
});
req.write(postData);
req.end(() => {
console.log('req end')
});
When i tried to api via postman, its working but if i PING using cmd, it say couldnt not find host. While i am trying the same with NODE JS getting the below error
Error: socket hang up
at connResetException (internal/errors.js:607:14)
at TLSSocket.socketOnEnd (_http_client.js:499:23)
at TLSSocket.emit (events.js:388:22)
at endReadableNT (internal/streams/readable.js:1336:12)
at processTicksAndRejections (internal/process/task_queues.js:82:21) {
code: 'ECONNRESET'
}
Try this it might work for you.
var options = {
'method': 'POST',
'host': 'api.stripe.com',
'path': '/v1/charges',
'headers': {
'Authorization': 'Bearer sk_test_4eC39HqLyjWDarjtT1zdp7dc',
'Content-Type': 'application/x-www-form-urlencoded',
'content-length': Buffer.byteLength(postData)
}
};
http.request(options, function(res) {
res.setEncoding('utf8');
res.on('data', function (chunk) {
console.log('BODY: ' + chunk);
});
}).end();
I want to make a REST call and get the result out in a variable (access_token). My variable AFAIK is global. Why is my variable access_token undefined at the end, even though i get a result in the console ? I understand that this call is async, but I put a 'false' in the call.
var https = require('https'),
querystring = require('querystring');
require('request-to-curl');
// First, get access token
var postData = querystring.stringify({
'grant_type': 'password',
'username':'<myusername>',
'password':'<mypassword>'
});
var options = {
hostname: 'myserver.com',
port: 443,
path: '/v1/oauth2/token',
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Content-Length': postData.length
}
};
function postVal(options, value) {
//var responseObject;
var access_token;
var responseObject;
var req = https.request(options, function(res)
{
res.setEncoding('utf-8');
var responseString = '';
res.on('data', function(data) {
responseString += data;
});
res.on('end', function() {
console.log(responseString);
responseObject = (JSON.parse(responseString));
access_token = responseObject.access_token;
console.log('console access:' + access_token);
value(access_token);
// return responseObject;
});
});
req.on('error', (e) => {
console.log(`problem with request: ${e.message}`);
});
// write data to request body
req.write(postData);
req.end();
}
console.log("Access:"+ postVal(options, function(access) {
console.log(access);
}));
Result:
$ node curl.js
Access:undefined
{"token_type":"Bearer","access_token":"f3DzDqW..dbMo0","refresh_token":"4jXqo4..kuuc2rMux3","scope":"global","access_token_type":"USER_GENERATED","note":"","expires_in":900}
console access:f3DzDqWpnrgxnxt5vE42ih8ew..gOKyJY5dbMo0
mlieber-ltm12:
var http = require('http');
var querystring = require('querystring');
var request = require('request');
var postData = querystring.stringify({
msg: 'hello world'
});
var request = require('req')
var options = {
hostname: 'localhost',
port: 8000,
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Content-Length': postData.length
}
};
var req = http.request(options, function(res) {
console.log('STATUS:', res.statusCode);
console.log('HEADERS:', JSON.stringify(res.headers));
res.setEncoding('utf8');
res.on('data', function(chunk) {
console.log('BODY:', chunk);
});
res.on('end', function() {
console.log('No more data in response.');
});
});
when i run this code I am getting cannot find 'req' module .I could see all the modules are properly installed in package.json and i did npm install too.Is there any problem in the code ?
Get rid of this line: var request = require('req')
You need to delete var request = require('req');
I am working on an app that uses the Microsoft Bot Framework. My app is written in Node. At this time, I am trying to POST an activity using the following code:
var https = require('https');
var token = '[receivedToken]';
var conversationId = '[conversationId]';
var options = {
host: 'directline.botframework.com',
port: 443,
headers: {
'Authorization': 'Bearer ' + token'
},
path: '/v3/directline/conversations/' + conversationId + '/activities',
method: 'POST'
};
var request = https.request(options, (res) => {
console.log(res.statusCode);
var body = [];
res.on('data', (d) => {
body.push(d);
});
res.on('end', () => {
var result = JSON.parse(Buffer.concat(body).toString());
console.log(result);
});
});
var info = {
type: 'message',
text: 'test',
from: { id: 'user_' + conversationId }
};
request.write(querystring.stringify(info));
request.end();
request.on('error', (err) => {
console.log(err);
});
When this code is ran, I receive an error. It's an error of status code 400 which has the following:
{
error: {
code: 'MissingProperty',
message: 'Invalid or missing activities in HTTP body'
}
}
I don't understand what property is missing though. Everything looks correct.
You missed Content-Type and Content-Length in your request headers.
Please consider the following code snippet:
var https = require('https');
var token = '[receivedToken]';
var conversationId = '[conversationId]';
var info = JSON.stringify({
type: 'message',
text: 'test',
from: { id: 'user_' + conversationId }
})
var options = {
host: 'directline.botframework.com',
port: 443,
headers: {
'Authorization': 'Bearer ' + token,
'Content-Type': 'application/json',
'Content-Length': Buffer.byteLength(info)
},
path: '/v3/directline/conversations/' + conversationId + '/activities',
method: 'POST'
};
var request = https.request(options, (res) => {
console.log(res.statusCode);
var body = [];
res.on('data', (d) => {
body.push(d);
});
res.on('end', () => {
var result = JSON.parse(Buffer.concat(body).toString());
console.log(result);
});
});
request.write(info);
request.end();
request.on('error', (err) => {
console.log(err);
});
I am trying to write a basic REST Post client to work with node.js and because of the REST API I have to work with I have to get details from the responses including cookies to maintain the state of my REST session with the server. My Question is what is the best way to pull the json objects from the response when res.on triggers with all the data in the PRINTME variable and return it to the test.js console.log().
test.js file
var rest = require('./rest');
rest.request('http','google.com','/upload','data\n');
console.log('PRINTME='JSON.stringify(res.PRINTME));
rest.js module
exports.request = function (protocol, host, path, data, cookie){
var protocalTypes = {
http: {
module: require('http')
, port: '80'
}
, https: {
module: require('https')
, port: '443'
}
};
var protocolModule = protocalTypes[protocol].module;
var options = {
host: host,
port: protocalTypes[protocol].port,
path: path,
method: 'POST',
headers: {
'Content-Type': 'text/xml'
, 'Content-Length': Buffer.byteLength(data)
, 'Cookie': cookie||''
}
};
console.log('cookies sent= '+options.headers.Cookie)
var req = protocolModule.request(options, function(res) {
var PRINTME = res;
console.log('STATUS: ' + res.statusCode);
console.log('HEADERS: ' + JSON.stringify(res.headers));
res.setEncoding('utf8');
res.on('data', function (chunk) {
PRINTME.body = chunk;
console.log('BODY: ' + chunk);
});
res.on('close', function () {res.emit('end')});
});
req.on('error', function(e) {
console.error('Request Failure: ' + e.message);
});
req.write(data);
req.end();
};
Using a package like request will help you simplify your code.
The following would be rest.js
var request = require('request');
module.exports = function(protocol, host, path, data, cookie, done) {
var options = {
host: host,
port: protocalTypes[protocol].port,
path: path,
method: 'POST',
headers: {
'Content-Type': 'text/xml',
'Content-Length': Buffer.byteLength(data)
},
jar: true
};
request(options, function(err, resp, body) {
if (err) return done(err);
// call done, with first value being null to specify no errors occured
return done(null, resp, body);
});
}
Setting jar to true will remember cookies for future use.
See this link for more information on the available options
https://github.com/mikeal/request#requestoptions-callback
To use this function in another file
var rest = require('./rest');
rest(... , function(err, resp, body){
...
});