Below in this example, in the variable 'obj' i get body of response. How to get header values of response using this https node.js library?
var options = {
hostname: hostname,
port: port,
path: pathMethod,
method: method,
headers: {
'Content-Type': APPLICATION_JSON,
'Authorization': BEARER + localStorage.jwtToken
},
rejectUnauthorized: false,
agent: false,
requestCert: false
};
return new Promise(function(resolve, reject) {
var req = https.request(options, function(res) {
res.setEncoding(ENCODING_UTF8);
res.on('data', function(result) {
try {
const obj = JSON.parse(result);
resolve({ 'httpStatus': PAGE_STATUS_200, 'result': obj });
}
catch(error) {
console.error(error);
resolve(resolve({ 'httpStatus': PAGE_STATUS_500 }));
}
});
res.on('end', () => {
console.log('No more data in response.');
});
});
req.on('error', function(err) {
console.log(`problem with request: ${err.message}`);
reject(err);
});
if (postData) {
req.write(postData);
}
req.end();
});
In my browser i get all necessary headers. What could be the problem that i can not get headers with https node.js lib?
You can get the headers in https module.
This is how you get the headers for the response.
res.headers
I have updated your code in example below:
var req = https.request(options, function(res) {
res.setEncoding(ENCODING_UTF8);
res.on('data', function(result) {
console.log("Headers: ", res.headers);
// Your code here.
});
res.on('end', () => {
// Do something here.
});
});
Hope this helps.
The response headers should be available in the res.headers object, e.g.
// Log headers
console.log('Headers: ', res.headers);
See: https://nodejs.org/api/https.html
e.g.
const https = require ('https');
// This will return the IP address of the client
var request = https.request({ hostname: "httpbin.org", path: "/ip" }, (res) => {
console.log('Headers: ', res.headers);
res.on('data', (d) => {
console.log('/ip response: ', d.toString());
});
});
// Also try using Request library
var request = require('request');
var options = {
url: "https://httpbin.org/ip",
method: "get"
};
console.log('Requesting IP..');
request(options, function (error, response, body) {
if (error) {
console.error('error:', error);
} else {
console.log('Response: Headers:', response && response.headers);
}
});
Related
I was using Azure Speech rest api. And i tried it on post man with a .wav file and it successfully return the result. However, when i call api from my node.js code. It always return Unsupported Audio Format even though i give the same audio file. Can anyone tell me what's the difference of them? Or what did Postman do to make it work?
Below is how i call speech api by node.js.
'use strict';
const request = require('request');
const subscriptionKey = 'MYSUBSCRIPTIONKEY';
const uriBase = 'https://westus.stt.speech.microsoft.com/speech/recognition/conversation/cognitiveservices/v1?language=en-US';
const options = {
uri: uriBase,
body: 'speech.wav',
headers: {
'Content-Type': 'application/json',
'Ocp-Apim-Subscription-Key' : subscriptionKey,
'Transfer-Encoding': 'chunked',
'Expect': '100-continue',
'Content-type':'audio/wav; codec=audio/pcm; samplerate=16000'
}
};
request.post(options, (error, response, body) => {
if (error) {
console.log('Error: ', error);
return;
}
let jsonResponse = JSON.stringify(JSON.parse(body), null, ' ');
console.log('JSON Response\n');
console.log(jsonResponse);
});
You can try this
fs.readFile('/path/to/my/audiofile.wav', function (err, data) {
if (err) throw err;
var options = {
host: 'https://westus.stt.speech.microsoft.com/speech/recognition/conversation/cognitiveservices/v1?language=en-US',
method: 'POST',
headers: { 'Content-Type': 'audio/wav' }
};
var req = http.request(options, function(res) {
// Handle a successful response here...
});
req.on('error', function(e) {
// Handle an error response here...
});
// Write the audio data in the request body.
req.write(data);
req.end();
});
This is my code, When i run it in lambda. It works fine but when i run it on my local server it's giving error [line 22: Uncaught SyntaxError: Unexpected token =>]
This is my first JS. :)
can someone please help me to understand this error.
Thanks!
"use strict";
const https = require('https');
const querystring = require('querystring');
const data = querystring.stringify({
'input' : 'test is passed'
});
const options = {
hostname: 'abc.xyz',
port: 443,
path: '/DEV/-testresult',
method: 'POST',
headers: {
'Content-Type' : 'application/json',
'x-api-key' : 'xxxxxx',
'X-Amz-Invocation-Type' : 'Event'
}
};
const req = https.request(options, (res) => {
let body = '';
console.log('Status:', res.statusCode);
console.log('Headers:', JSON.stringify(res.headers));
res.setEncoding('utf8');
res.on('data', (chunk) => body += chunk);
res.on('end', () => {
console.log('Successfully processed HTTPS response');
// If we know it's JSON, parse it
if (res.headers['content-type'] === 'application/json') {
body = JSON.parse(body);
}
});
});
req.on('error');
req.write(JSON.stringify(data));
req.end();
Use function instead on Arrow function. it will work.
const req = https.request(options, **function**(res){
let body = '';
console.log('Status:', res.statusCode);
console.log('Headers:', JSON.stringify(res.headers));
res.setEncoding('utf8');
res.on('data', (chunk) => body += chunk);
res.on('end', () => {
console.log('Successfully processed HTTPS response');
// If we know it's JSON, parse it
if (res.headers['content-type'] === 'application/json') {
body = JSON.parse(body);
}
});
});
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 want to post from server consider as proxy to another server with promises. I wrote this code but it does not work, I think the manner with connect with two servers is true:
function test(req, res) {
var pro = getPromiseP();
pro.then(function(data) {
res.send(data);
}).catch(function(err) {
console.log(err);
})
}
function getPromiseP(){
var options = {
host: 'localhost',
port: 3000,
path: '/btest',
method:'POST',
headers: {
'Content-Type': 'application/json'
},
body:{
'id':1,
'name':'name4'
}
};
var promise = new Promise(function(resolve, reject) {
var req = http.request(options,function(res) {
res.on('data', function(body) {
var data = '';
data += body;
resolve(data);
return;
});
});
req.on('error', function(e) {
console.log('problem with request: ' + e.message);
reject(e);
});
});
return promise;
}
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){
...
});