ENOTFOUND issue on https get request - javascript

In my application I'm trying to hit an end point using https and then getting the response.
Route file:
router.get("/get-details", (req, res) => {
sampleController.getDetails()
.then((data) => {
console.log("Data is ", data);
res.send(data);
})
.catch(() => {
res.status(500).json({
success: false,
data: null,
message: "Failed to lookup the data",
});
});
});
Controller file:
const getDetials = () => {
return new Promise((resolve, reject) => {
const options = {
hostname: "https://jsonplaceholder.typicode.com/",
path: "posts",
method: "GET",
};
const req = https.request(options, (res) => {
console.log(`statusCode: ${res.statusCode}`);
res.on("data", (d) => {
process.stdout.write(d);
});
});
req.on("error", (error) => {
console.log("Error is ", error);
reject(error);
});
req.end();
});
};
I am getting this error:
Not sure where I'm making the mistake. Does somebody know what I'm getting wrong here?

Try setting up the URL without the protocol and add / in front of the path in options object:
const options = {
hostname: "jsonplaceholder.typicode.com",
path: "/posts",
method: "GET",
};
Full example:
const getDetials = () => {
return new Promise((resolve, reject) => {
const options = {
hostname: "jsonplaceholder.typicode.com",
path: "/posts",
method: "GET",
};
const req = https.request(options, (res) => {
console.log(`statusCode: ${res.statusCode}`);
res.on("data", (d) => {
process.stdout.write(d);
});
});
req.on("error", (error) => {
console.log("Error is ", error);
reject(error);
});
req.end();
});
};

Related

How do I need to collect my data in the object for post request?

I just want to send request, but in the end of function my object is{img:'',text: ''}.
I expect to get .jpg file name in obj.img and text inside .txt file in obj.text. So here we go:
Maybe it's something about scope. I don't know.
const path = require('path');
const fs = require('fs');
const request = require('request');
const axios = require('axios');
let shortcode = '';
async function getData() {
const obj = {
img: '',
text: '',
};
await fetch('http://127.0.0.1:8000/api')
.then(response => response.json())
.then(data => (shortcode = data[data.length - 1].shortcode));
fs.readdir(
`path/${shortcode}`,
(err, data) => {
if (err) {
throw err;
}
data.forEach(file => {
if (path.extname(file) === '.jpg') {
obj.img = file;
} else if (path.extname(file) === '.txt') {
fs.readFile(
`path/${shortcode}/${file}`,
'utf-8',
(err, data) => {
if (err) {
throw err;
}
obj.text = data;
console.log(data);
},
);
}
});
},
);
console.log(obj);
await fetch('http://127.0.0.1:8000/instaData', {
method: 'POST',
body: JSON.stringify({
img: obj.img,
text: obj.text,
}),
headers: {
'Content-Type': 'application/json;charset=utf-8',
},
});
}
getData();

How to get multiple values out of resolve() and reject()?

I would like both resolve() to return {valid_to: cert.valid_to, statusCode, statusMessage} and reject() should return {error: -1, statusCode, statusMessage}.
Question
How can I do that, when statusCode, statusMessage are in a different scope?
const https = require('https');
(async () => {
const options = {
hostname: "github.com",
port: 443,
path: '/',
method: 'GET',
timeout: 1000
};
options.agent = new https.Agent(options);
let valid_to = await new Promise((resolve, reject) => {
const req = https.request({
...options, checkServerIdentity: function (host, cert) {
resolve(cert.valid_to);
}
}).on('error', error => {
reject(-2);
});
req.on("timeout", chunk => {
reject(-1);
});
req.on('response', response => {
console.log(response.statusCode);
console.log(response.statusMessage);
});
req.end();
}).catch(error => {
console.log(error);
return -3;
});
})();
I will do something like this.
Edit: You need to specify res.on('data') in the https.request Object. Otherwise, timeout will always emit because there is no activity from the stream.
You can resolve in res.on("data") or res.on("end") and it is up to your use case.
res is an IncomingMessage object is created by http.ClientRequest and passed as the first argument to the 'request' and 'response' event respectively.
req is A reference to the original http.ClientRequest.
Both streams can emit events and you may handle them separately.
Also, when you reject the Promise, you actually cannot get the statusCode and StatusMessage from the req because there is an error in the req and the .on("response") will not be emitted. So, you need to customize the statusCode and statusMessage yourself.
const https = require("https");
// {valid_to: cert.valid_to, statusCode, statusMessage}
// {error: -1, statusCode, statusMessage}.
(async () => {
const options = {
hostname: "githubasdfa.com",
port: 443,
path: "/",
method: "GET",
timeout: 1000,
};
options.agent = new https.Agent(options);
try {
const response = await new Promise((resolve, reject) => {
let valid_to;
let statusCode;
let statusMessage;
const req = https
.request(
{
...options,
checkServerIdentity: function (host, cert) {
valid_to = cert.valid_to;
},
},
res => {
res.on("data", chunk => {
resolve({
valid_to,
statusCode,
statusMessage,
});
});
res.on("end", () => {
console.log("No more data in response.");
});
}
)
.on("error", err => {
console.log(err);
reject({
error: -2,
statusCode: "custom code",
statusMessage: "unhandled error",
});
})
.on("timeout", chunk => {
reject({
error: -1,
statusCode: "custom code",
statusMessage: "unhandled error",
});
})
.on("response", response => {
statusCode = response.statusCode;
statusMessage = response.statusMessage;
})
.end();
});
console.log(response);
} catch (error) {
console.log(error);
}
})();

Internal Server Error: No suitable HttpMessageConverter found for response type

status: 500, error: "Internal Server Error"
message: Could not extract response: no suitable HttpMessageConverter found for response type [class com.clone.instagram.authservice.fetchdata.model.Example] and content type [text/html;charset=utf-8]"
So strangely this error has started showing up while accessing insta API,
What's strange is this happens "only sometimes",
And never happened before.
It works some times, some times it pops this error
const request = (options) => {
const headers = new Headers();
headers.append("Content-Type", "application/json");
if (localStorage.getItem("accessToken")) {
headers.append(
"Authorization",
"Bearer " + localStorage.getItem("accessToken")
);
}
const defaults = { headers: headers };
options = Object.assign({}, defaults, options);
return fetch(options.url, options).then((response) =>
response.json().then((json) => {
if (!response.ok) {
return Promise.reject(json);
}
return json;
})
);
};
export function registerInstaUserInfo(instaUserINfoRequest){
if (!localStorage.getItem("accessToken")) {
return Promise.reject("No access token set.");
}
console.log("inside getInstaUserInfo request ");
return request({
url: properties.INSTA_USER_REGISTER ,
method: "POST",
body: JSON.stringify(instaUserINfoRequest),
});
}
const getInstaUserInfoFromService = (response) => {
//store respose.data
if (response.data.user_id) {
console.log("setting up insta user staate ", response.data);
localStorage.setItem("insta_user", response.data);
cookies.set("insta_user", response.data, { path: "/" });
console.log("cookies ", cookies.get("insta_user"));
const fb_access_token = localStorage.getItem("accessToken");
console.log("fb_access_token", fb_access_token);
const user_info = registerInstaUserInfo(response.data)
.then((res) => {
console.log(res);
setLinkedInstaAccounts([...linkedAccounts, res]);
})
.catch((err) => console.error("Hello stackoverlflowpeople this is where error happens", err));
console.log("user_info", user_info);
props.history.push("/home");
//redirecting to account.js
// props.history.push("/me");
}
};
const successResponse = (code) => {
console.log("inside success func");
console.log(code);
var bodyFormData = new FormData();
bodyFormData.append("redirect_uri", properties.INSTA_REDIRECT_URL);
bodyFormData.append("code", code);
bodyFormData.append("client_id", properties.INSTA_CLIENT_ID);
bodyFormData.append("client_secret", properties.INSTA_CLIENT_SECRECT);
bodyFormData.append("grant_type", "authorization_code");
axios({
method: "post",
url: properties.INSTA_ACCESS_TOKEN_URL,
data: bodyFormData,
headers: {
"Content-Type": "multipart/form-data",
Accept: "application/vnd.api+json",
},
})
.then(getInstaUserInfoFromService)
.catch(function (response) {
//handle error
console.log(response);
});
};
----
//component
<InstagramLogin
clientId={properties.INSTA_CLIENT_ID}
buttonText="Login"
redirectUri={properties.INSTA_REDIRECT_URL}
scope="user_profile,user_media"
onSuccess={successResponse}
onFailure={failedresponseInstagram}
/>
=====================THIS getInstaUserFromService is where error happens
const getInstaUserInfoFromService = (response) => {
//store respose.data
if (response.data.user_id) {
console.log("setting up insta user staate ", response.data);
localStorage.setItem("insta_user", response.data);
cookies.set("insta_user", response.data, { path: "/" });
console.log("cookies ", cookies.get("insta_user"));
const fb_access_token = localStorage.getItem("accessToken");
console.log("fb_access_token", fb_access_token);
const user_info = registerInstaUserInfo(response.data)
.then((res) => {
console.log(res);
setLinkedInstaAccounts([...linkedAccounts, res]);
})
.catch((err) => console.error("Hello stackoverlflowpeople this is where error happens", err));
console.log("user_info", user_info);
props.history.push("/home");
//redirecting to account.js
// props.history.push("/me");
}
};
I was using this but I have not touched headers or anything, is it something with Instagram server?

Use a value from a function into another function nodejs express

I want to return the value that has been declared in the first Function CreateTag and using it as variable in the second Function CreateStream, but it won't work..
I'm working with nodejs Express.
I try to use RETURN but it won't work..
I have tried it in differance ways, but still not work..
Can you someone help me, please?
'use strict';
var express = require('express');
var router = express.Router();
/* GET home page. */
//Function 1: createTag
var createTag = function hi (TanentValue) {
var https = require('https');
var data = JSON.stringify({
name: TanentValue,
schemaPath: "Tag"
});
var options = {
hostname: 'qlik_dev.be',
path: '/meteor/qrs/tag?xrfkey=1234567890123456',
method: 'POST',
headers: {
'x-qlik-xrfkey': '1234567890123456',
'hdr-usr': 'gak\\gaka',
'Content-Type': 'application/json'
},
};
var req = https.request(options, (res) => {
//console.log(res)
res.on('data', (d) => {
console.log("hi tag")
var getResult = "GaLvAnI"; // ----> return this and use it into the function createStream
return getResult;
})
})
;
req.on('error', (error) => {
console.error(error)
});
req.write(data);
req.end();
}
//Function 2: createStream
var createStream = function (TanentValue) {
var https = require('https');
var galvani = hi(); // --------> here I made a variable to call return value
var data = JSON.stringify({
name: TanentValue,
});
var options = {
hostname: 'qlik_dev.be',
path: '/meteor/qrs/stream?xrfkey=1234567890123456',
method: 'POST',
headers: {
'x-qlik-xrfkey': '1234567890123456',
'hdr-usr': 'gak\\gaka',
'Content-Type': 'application/json'
},
};
var req = https.request(options, (res) => {
res.on('data', (d) => {
console.log(galvani); // -----> use the variable here
})
})
;
req.on('error', (error) => {
console.error(error)
});
req.write(data);
req.end();
}
//homepage
router.get('/', function (req, res) {
res.render('index', { title: 'MCS Test' });
});
//create
router.post('/create', function (req, res) {
//create tag
console.log('POST / Call Create Tag');
createTag(req.body.TanentValue);
//create stream
console.log('POST / Call Create Stream');
createStream(req.body.TanentValue);
res.send('Stream and Tag has been created');
});
module.exports = router;
you can not directly return value from async function. you have to use promise. something like this:
'use strict';
var express = require('express');
var router = express.Router();
/* GET home page. */
//Function 1: createTag
var createTag = function (TanentValue) { // function should be anonymouse
return new Promise((resolve, reject) => {
var https = require('https');
var data = JSON.stringify({
name: TanentValue,
schemaPath: "Tag"
});
var options = {
hostname: 'qlik_dev.be',
path: '/meteor/qrs/tag?xrfkey=1234567890123456',
method: 'POST',
headers: {
'x-qlik-xrfkey': '1234567890123456',
'hdr-usr': 'gak\\gaka',
'Content-Type': 'application/json'
},
};
var req = https.request(options, (res) => {
//console.log(res)
res.on('data', (d) => {
console.log("hi tag")
var getResult = "GaLvAnI"; // ----> return this and use it into the function createStream
resolve(getResult); // success call
})
})
;
req.on('error', (error) => {
reject(error); // error call
});
req.write(data);
req.end();
});
}
//Function 2: createStream
var createStream = function (TanentValue) {
createTag().then((val) => {
var https = require('https');
var galvani = val; // use that value from sucess call
var data = JSON.stringify({
name: TanentValue,
});
var options = {
hostname: 'qlik_dev.be',
path: '/meteor/qrs/stream?xrfkey=1234567890123456',
method: 'POST',
headers: {
'x-qlik-xrfkey': '1234567890123456',
'hdr-usr': 'gak\\gaka',
'Content-Type': 'application/json'
},
};
var req = https.request(options, (res) => {
res.on('data', (d) => {
console.log(galvani); // -----> use the variable here
})
})
;
req.on('error', (error) => {
console.error(error)
});
req.write(data);
req.end();
})
.catch((error) => {
// handle error from createTag function here
});
}
//homepage
router.get('/', function (req, res) {
res.render('index', { title: 'MCS Test' });
});
//create
router.post('/create', function (req, res) {
//create tag
console.log('POST / Call Create Tag');
createTag(req.body.TanentValue);
//create stream
console.log('POST / Call Create Stream');
createStream(req.body.TanentValue);
res.send('Stream and Tag has been created');
});
module.exports = router;
You can solve it using just callback function or the promise.
Using callbacks.
'use strict';
var express = require('express');
var router = express.Router();
/* GET home page. */
//Function 1: createTag
var createTag = (TanentValue, callback) => {
var https = require('https');
var data = JSON.stringify({
name: TanentValue,
schemaPath: "Tag"
});
var options = {
hostname: 'qlik_dev.be',
path: '/meteor/qrs/tag?xrfkey=1234567890123456',
method: 'POST',
headers: {
'x-qlik-xrfkey': '1234567890123456',
'hdr-usr': 'gak\\gaka',
'Content-Type': 'application/json'
},
};
var req = https.request(options, (res) => {
res.on('data', (d) => {
console.log("hi tag")
var getResult = "GaLvAnI"; // ----> return this and use it into the function createStream
callback(false, getResult);
})
});
req.on('error', (error) => {
//console.error(error)
callback(true, error);
});
req.write(data);
req.end();
}
//Function 2: createStream
var createStream = (TanentValue, callback) => {
var https = require('https');
var data = JSON.stringify({
name: TanentValue,
});
var options = {
hostname: 'qlik_dev.be',
path: '/meteor/qrs/stream?xrfkey=1234567890123456',
method: 'POST',
headers: {
'x-qlik-xrfkey': '1234567890123456',
'hdr-usr': 'gak\\gaka',
'Content-Type': 'application/json'
},
};
createTag(TanentValue, (is_error, galvani) => {
if(err || !data){
// do error handling...
callback(true); // true for there was an error
}else{
var req = https.request(options, (res) => {
res.on('data', (d) => {
callback(false);
console.log(galvani); // -----> use the variable here
})
});
req.on('error', (error) => {
callback(true);
console.error(error)
});
req.write(data);
req.end();
}
})
}
//homepage
router.get('/', function (req, res) {
res.render('index', { title: 'MCS Test' });
});
//create
router.post('/create', function (req, res) {
/*
// Since the stream seems to depend on the tag created,
// you don't need to call createTag explicitly because
// it is always/already called from createStream.
//create tag
console.log('POST / Call Create Tag');
createTag(req.body.TanentValue, function(is_error, data){
if(!is_error){
// do something
}else{
// do error handling
console.error(error);
res.send('Tag could not be created, please try later again..');
}
});
*/
//create stream
console.log('POST / Call Create Stream');
createStream(req.body.TanentValue, is_error => {
if(!is_error){
res.send('Stream and Tag has been created');
}else{
res.send('Stream could not be created, please try later again..');
}
});
});
module.exports = router;
Using Promise
'use strict';
var express = require('express');
var router = express.Router();
/* GET home page. */
//Function 1: createTag
var createTag = TanentValue => {
var https = require('https');
var data = JSON.stringify({
name: TanentValue,
schemaPath: "Tag"
});
var options = {
hostname: 'qlik_dev.be',
path: '/meteor/qrs/tag?xrfkey=1234567890123456',
method: 'POST',
headers: {
'x-qlik-xrfkey': '1234567890123456',
'hdr-usr': 'gak\\gaka',
'Content-Type': 'application/json'
},
};
return new Promise((resolve, reject) => {
var req = https.request(options, (res) => {
res.on('data', (d) => {
console.log("hi tag")
var getResult = "GaLvAnI"; // ----> return this and use it into the function createStream
resolve(getResult);
})
});
req.on('error', (error) => {
//console.error(error)
reject(error);
});
req.write(data);
req.end();
})
}
//Function 2: createStream
var createStream = TanentValue => {
var https = require('https');
var data = JSON.stringify({
name: TanentValue,
});
var options = {
hostname: 'qlik_dev.be',
path: '/meteor/qrs/stream?xrfkey=1234567890123456',
method: 'POST',
headers: {
'x-qlik-xrfkey': '1234567890123456',
'hdr-usr': 'gak\\gaka',
'Content-Type': 'application/json'
},
};
createTag(TanentValue).then( galvani => {
return new Promise((resolve, reject) => {
var req = https.request(options, (res) => {
res.on('data', (d) => {
console.log(galvani); // -----> use the variable here
resolve(d);
})
});
req.on('error', (error) => {
console.error(error)
reject({ msg: 'request error while creating the stream', error: error})
});
req.write(data);
req.end();
})
}).catch( error => {
// do error handling...
reject({msg: 'Error while creating a tag', error: error}); // true for there was an error
});
}
//homepage
router.get('/', function (req, res) {
res.render('index', { title: 'MCS Test' });
});
//create
router.post('/create', function (req, res) {
/*
// Since the stream seems to depend on the tag created,
// you don't need to call createTag explicitly because
// it is always/already called from createStream.
//create tag
console.log('POST / Call Create Tag');
createTag(req.body.TanentValue).then( data => {
// do something
}).catch( error => {
// do error handling
});
*/
//create stream
console.log('POST / Call Create Stream');
createStream(req.body.TanentValue).then( data => {
res.send('Stream and Tag has been created');
}).catch(error => {
// 'Stream could not be created, please try later again..'
res.send(error.msg);
});
});
module.exports = router;
Very handfull!! thank you it works!
But while passing the data (Json) from function 1 to function 2 with Promise, the data (json) is undefine in function 2. If I pass a data (String) from function 1 to function 2 than it works..
Why does it give me 'undefine' when it is a json?
//var id;
var req = https.request(options, (res) => {
//console.log(res)
res.setEncoding('utf8');
res.on('data', function (data) {
var json = JSON.parse(data);
var TagId = JSON.stringify(json[0]);
console.log("2 hi getTap");
console.log(TagId); // -------> here it works well
resolve(TagId);
});
});
var req = https.request(options, (res) => {
res.on('data', (d) => {
console.log("3 hi createStream");
console.log(galvani); // -------> here it doesn't work.. it gives me undefine
})
});
here a printscreen of response

When uploading two images, console.log(parsedRes) only returns one object instead of (the expected) two

So, I'm trying to fetch base64 data (urls) from two images I uploaded to the cloud/server, but when I parsed the response, I only get 1 object instead of 2 (i.e. only the url for the first image).
I must be overseeing something fundamentally, but I can't see it. Appreciate the advice.
Can some help explain to me why the code below doesn't work?
[EDIT: I've included the server code. Hopefully this makes it clearer as to the problem I'm facing]
.then(token => {
authToken = token;
return fetch("myappURL/storeImage",
{
method: "POST",
body: JSON.stringify({
image: image.base64,
coverImage: coverImage.base64
}),
headers: { Authorization: "Bearer " + authToken }
});
})
.catch(err => {
console.log(err);
alert("Oops! Something went wrong, please try again1")
dispatch(uiStopLoading());
})
.then(res => {
if (res.ok) {
return res.json();
} else {
throw(new Error());
}
})
.then(parsedRes => {console.log(parsedRes)}); // I only get 1 result instead of 2 (why?!)
Server-side code:
exports.storeImage = functions.https.onRequest((request, response) => {
return cors(request, response, () => {....
.then(decodedToken => {
const body = JSON.parse(request.body);
fs.writeFileSync("/tmp/uploaded-image.jpg", body.image, "base64", err => {
console.log(err);
return response.status(500).json({ error: err });
});
const bucket = gcs.bucket("myapp.appspot.com");
const uuid = UUID();
return bucket.upload(
"/tmp/uploaded-image.jpg",
{
uploadType: "media",
destination: "/places/" + uuid + ".jpg",
metadata: {
metadata: {
contentType: "image/jpeg",
firebaseStorageDownloadTokens: uuid
}
}
},
(err, file) => {
if (!err) {
return response.status(201).json({ // I get this returned
imageUrl:
"https://firebasestorage.googleapis.com/v0/b/" +
bucket.name +
"/o/" +
encodeURIComponent(file.name) +
"?alt=media&token=" +
uuid,
imagePath: "/places/" + uuid + ".jpg"
});
} else {
console.log(err);
return response.status(500).json({ error: err });
}
}
);
})
.catch(error => {
console.log("Token is invalid!");
response.status(403).json({error: "Unauthorized"});
})
.then(decodedToken => {
const body = JSON.parse(request.body);
fs.writeFileSync("/tmp/uploaded-coverImage.jpg", body.coverImage, "base64", err => {
console.log(err);
return response.status(500).json({ error: err });
});
const bucket = gcs.bucket("myapp.appspot.com");
const uuid = UUID();
return bucket.upload(
"/tmp/uploaded-coverImage.jpg",
{
uploadType: "media",
destination: "/coverPlaces/" + uuid + ".jpg",
metadata: {
metadata: {
contentType: "coverImage/jpeg",
firebaseStorageDownloadTokens: uuid
}
}
},
(err, coverFile) => {
if (!err) {
return response.status(201).json({ // I do NOT get this returned (why not?!)
coverImageUrl:
"https://firebasestorage.googleapis.com/v0/b/" +
bucket.name +
"/o/" +
encodeURIComponent(coverFile.name) +
"?alt=media&token=" +
uuid,
coverImagePath: "/coverPlaces/" + uuid + ".jpg"
});
} else {
console.log(err);
return response.status(500).json({ error: err });
}
}
);
})
.catch(error => {
console.log("Token is invalid!");
response.status(403).json({error: "Unauthorized"});
});
});
});

Categories

Resources