Node Express Get request passing a custom header - node.js

I am trying to make a get request equivalent to this jQuery:
$.ajax({
headers: { 'X-Auth-Token': 'YOUR_API_KEY' },
url: 'http://api.football-data.org/v2/competitions/BL1/standings',
dataType: 'json',
type: 'GET',
}).done(function(response) {
console.log(response);
});
However, I haven't figured out how to do it using nodejs - express. This code is from an api routes module attached to the main app.
The request seems to work, collecting the data but does not end. Also, I cannot see the custom header in the request when inspecting from the browser.
app.get('/api/:league', function(req, res, next) {
var apiKey = process.env.API_KEY;
let url = 'api.football-data.org';
var options = {
host: url,
method: 'GET',
path: 'v2/competitions/BL1/standings',
headers: {
'X-Auth-Token': apiKey
}
};
let data = "";
var getReq = http.request(options,function(resp){
console.log("Connected");
resp.on("data", chunk => {
data += chunk;
});
resp.on("end", () => {
console.log("data collected");
});
});
getReq.on("error", (err) => console.log("OOPS!", err));
getReq.end(JSON.stringify(data));
})
Link to project

Try using request-promise npm package.https://www.npmjs.com/package/request-promise
var rp = require(request-promise);
const baseUrl = 'api.football-data.org/v2/competitions/BL1/standings';
const apiKey = process.env.API_KEY;
var options = {
method: 'GET',
uri: baseUrl,
headers: {
'X-Auth-Token': apiKey
},
json: true
};
rp(options)
.then(function (response) {
console.log(response)
}
);

jQuery ajax function does not have headers option. You can read about this function on official doc http://api.jquery.com/jquery.ajax/ . They custom request header by beforeSend function way:
$.ajax({
beforeSend: function (request) {
request.setRequestHeader("X-Auth-Token", 'YOUR_API_KEY');
},
url: 'http://api.football-data.org/v2/competitions/BL1/standings',
dataType: 'json',
type: 'GET',
}).done(function (response) {
console.log(response);
});
With http node lib, you can flow this example
var req = http.request(options, function (res) {
var chunks = [];
res.on("data", function (chunk) {
chunks.push(chunk);
});
res.on("end", function () {
var body = Buffer.concat(chunks);
// TODO: send data to client
// res.status(200).json(JSON.stringify(body.toString()))
console.log(body.toString());
});
});
req.end();

Related

how to use access token to call another post request?

I have this post request to get access token and its working fine but would like to know how can I use this access token to call another post request ? Or how do I use async or promises to use in this ?
Here is my code :
function getAccessToken() {
const querystring = require('querystring');
const https = require('https')
const postData = querystring.stringify({
'grant_type': 'client_credentials'
});
const options = {
"hostname":'api.xxx.com',
"method": "POST",
"path" : "/token",
"port" : 443,
"encoding": "utf8",
"followRedirect": true,
"headers": {
"Authorization": 'Basic ' + Buffer.from("client_id" + ':' + "client_secret").toString('base64'),
"Content-Type": 'application/x-www-form-urlencoded',
"Content-Length": Buffer.byteLength(postData),
},
'muteHttpExceptions': true
}
const body = []
const req = https.request(options, res => {
console.log(`statusCode: ${res.statusCode}`)
res.on('data', (chunk) => body.push(chunk))
res.on('end', () => {
const access_token = Buffer.concat(body).toString()
console.log(access_token)
})
})
req.on('error', error => {
console.error(error)
})
req.write(postData);
req.end()
}
getAccessToken();
You can save token in database,file or other memory database and use it in all requests in the Authorization header but depends on type of token,for example for set JWT token:
request.setHeader('Authorization', 'Bearer '+accessToken)
OR in option object:
options = {
host: '<URL>',
path: '<path of endpoint>',
port: '<portNumber>',
headers: {'Authorization', 'Bearer '+accessToken}
};
also for the async request to another endpoint, you can use Axios axios example:
const axios = require('axios').default;
const sendGetRequest = async () => {
try {
const resp = await
axios.get('https://jsonplaceholder.typicode.com/posts', {
headers: {
'authorization': 'Bearer YOUR_JWT_TOKEN_HERE'
}
});
console.log(resp.data);
} catch (err) {
// Handle Error Here
console.error(err);
}
};
sendGetRequest();

How to send the result of a GET request in a POST request?

I need to send a GET request to https://random.dog/woof.json. It generate a random image and returns a json like this {
"fileSizeBytes": 1133380,
"url": "https://random.dog/8aff4e84-260d-4af0-9dc1-438d07ba3884.jpg"
} and I need save an image to my database. How can I take "url" and send it with POST request?
you can use node-fetch for server side requests.
It's similar to js' fetch api:
const fetch = require('node-fetch');
fetch('https://random.dog/woof.json')
.then(res => res.json())
.then(json => {
console.log("URL:", json[0].url);
fetch('<url for your post request>', {
method: 'POST',
body: { url: json[0].url },
headers: { 'Content-Type': 'application/json' }
}).then(postRes => postRes.json())
.then(postJson => console.log(postJson));
})
You can do something like that
const https = require('https')
function getData(url: String) {
const options = {
hostname: 'exemple.com',
path: '/your-endpoint',
method: 'POST',
headers: {
'Content-Type': 'application/json',
}
}
const req = https.request(options, (response: any) => {
let body = '';
response.on("data", (data: String) => {
body += data;
})
response.on("end", () => {
console.log(body)
})
response.on("error", (error: String) => {
console.error(error)
})
})
req.write(JSON.stringify({
url
}));
req.end()
}
https.get("https://random.dog/woof.json", (response: any) => {
let body = '';
response.on("data", (chunk: String) => {
body += chunk;
})
response.on("end", () => {
const obj = JSON.parse(body);
getData(obj.url)
})
});

NodeJS request get return me html code instead of json

I'm trying to get get a json from a get request it's work in python but in NodeJs that display me the html code source of the page
this is my code :
app.get("/well", function(request, response) {
const req = require('request');
const options = {
url: 'https://swarmmanager.francecentral.cloudapp.azure.com:3000',
method: 'GET',
headers: {
'Accept': 'application/json',
},
agentOptions: {
ca: fs.readFileSync("public/IdaktoPKIRootCA.crt")
}
};
req(options, function(err, res, body) {
console.log(body);
});
});
and this is another version but same problem:
app.get("/well", function(request, response) {
g_CnieOidcAddr = 'https://swarmmanager.francecentral.cloudapp.azure.com:3000';
const options = {
hostname: 'swarmmanager.francecentral.cloudapp.azure.com',
port: 3000,
method: 'GET',
headers: {
'Accept': 'application/json',
},
ca: fs.readFileSync("public/IdaktoPKIRootCA.crt")
};
const req = https.request(options, (res) => {
console.log('statusCode:', res.statusCode);
console.log('headers:', res.headers);
res.on('data', (d) => {
process.stdout.write(d);
});
});
req.on('error', (e) => {
console.error(e);
});
req.end();
});
i try to do it in python and it's work find that return me a json:
headers = {'Accept': 'application/json'}
r = requests.get(g_CnieOidcAddr + '/.well-known/openid-configuration', params={}, headers = headers, verify='./IdaktoPKIRootCA.crt')
print (r.text)
if anyone has an idea i'm a taker ^^ thanks for reading.
ok that work find i just forgot something at the end of the url so if you come to this page the 2 codes work find to to a request

Error: getaddrinfo ENOTFOUND error when making an HTTPS/HTTP request

Here's the code of my AWS Lambda function:
console.log('Loading function');
const AWS = require('aws-sdk');
const https = require('https');
const data = JSON.stringify({
secretKey:"someSecretKey",
userType:"someCoolUser",
})
const options = {
hostname: "backend-staging.programmingpathshala.com:8080/rest/admin",
path: '/sendEmailToUsers',
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Content-Length': data.length
}
}
exports.handler = function(event, context, callback) {
var dataString = '';
const req = https.request(options, function(res) {
res.on('data', chunk => {
dataString += chunk;
});
res.on('end', () => {
callback(null,dataString);
});
});
req.write(data)
req.end();
req.on('error', (e) => {
console.error(e);
});
}
When I test my API using postman it works fine. But when it is called from lambda function I get the following error:
Also, When I run the same API using ngrok and use its link in my lambda function it works then too.
Based on the comments, the options should be:
const options = {
hostname: "backend-staging.programmingpathshala.com",
port: 8080,
path: '/rest/admin/sendEmailToUsers',
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Content-Length': data.length
}
}

One Signal Push Notification

How to include small icon and big icon url while creating a push notification in node js, I know that we need to send image url while sending push notification, i need code sample in node js.. I have this code..
sendNotificationToSpecific =function (token,messages) {
var sendNotification = function (data) {
var headers = {
"Content-Type": "application/json; charset=utf-8",
"Authorization": "Basic MDNlMTNjYWMTgy"
};
var options = {
host: "onesignal.com",
port: 443,
path: "/api/v1/notifications",
method: "POST",
headers: headers
};
var https = require('https');
var req = https.request(options, function (res) {
res.on('data', function (data) {
console.log("Response:");
console.log(JSON.parse(data));
});
});
req.on('error', function (e) {
console.log("ERROR:");
console.log(e);
});
req.write(JSON.stringify(data));
req.end();
};
var message = {
app_id: "awer342-d744-4787-b59a-f55c6215c491",
contents: {"en": messages},
include_player_ids: [token],
};
sendNotification(message);
};
As you can see in the docs https://documentation.onesignal.com/reference#section-appearance you can simply extend your message object like
var message = {
app_id: "xxxx",
contents: {"en": messages},
include_player_ids: [token],
small_icon: "resource_name", // can not be an url
large_icon: "http://url/ or resource_name"
}

Resources