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);
}
});
});
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 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();
});
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);
}
});
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:
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);
});