How do you make this curl request in node - node.js

This curl request to the spotify API works perfectly fine
curl -X "POST" -H "Authorization: Basic <my-key-here>" -d grant_type=client_credentials https://accounts.spotify.com/api/token
I'm trying to do this in node, but it's not working and returns a 400 Bad Request. Here is my code. What am I doing wrong?
function AuthRequest(key) {
const req_body_params = JSON.stringify({
grant_type: "client_credentials"
})
const base64_enc = new Buffer(key).toString("base64")
const options = {
host: "accounts.spotify.com",
port: 443,
path: "api/token",
method: "POST",
headers: {
"Content-Type": "application/json",
"Authorization": `Basic ${base64_enc}`
}
}
const req = https.request(options, function (res) {
res.on('data', function (data) {
alert("success: " + data)
})
})
req.on('error', function (err) {
alert("error: " + err)
})
req.write(req_body_params)
req.end()
}
I'm trying to use the Client Credentials method as explained here: https://developer.spotify.com/web-api/authorization-guide/

The request should be in application/x-www-form-urlencoded instead of JSON, it should be const req_body_params = "grant_type=client_credentials" with a header of "Content-Type": "application/x-www-form-urlencoded"
function AuthRequest(key) {
const req_body_params = "grant_type=client_credentials";
const base64_enc = new Buffer(key).toString("base64");
const options = {
host: "accounts.spotify.com",
port: 443,
path: "/api/token",
method: "POST",
headers: {
"Content-Type": "application/x-www-form-urlencoded",
"Authorization": `Basic ${base64_enc}`
}
};
const req = https.request(options, function(res) {
res.on('data', function(data) {
alert("success: " + data)
})
});
req.on('error', function(err) {
alert("error: " + err)
});
req.write(req_body_params);
req.end();
}

Because token expires is good to request them dynamically, I created a method that output a token as a promise, then you can consume in your request.
const axios = require('axios')
const client_id = process.env.SPOTIFY_CLIENT_ID;
const client_secret = process.env.SPOTIFY_CLIENT_SECRET;
function getToken( ) {
return axios({
url: 'https://accounts.spotify.com/api/token',
method: 'post',
params: {
grant_type: 'client_credentials'
},
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
auth: {
username: client_id,
password: client_secret
}
})
}
async function getSpotifyData( endpoint ){
const tokenData = await getToken( );
const token = tokenData.data.access_token;
axios({
url: `https://api.spotify.com/v1/${endpoint}`,
method: 'get',
headers: {
'Authorization': 'Bearer ' + token
}
}).then( response => {
console.log( response.data );
return response.data;
}).catch( error => {
throw new Error(error);
});
}
getSpotifyData( 'browse/new-releases' );

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

Send post request with Axios with body and headers

I am working on a project where I need to create a short URL for a link using bitly.
I got success by using the request package of Nodejs.
This is what I have done so far.
const token = process.env.BITLY_ACCESS_TOKEN;
let headers = {
Authorization: `Bearer ${token}`,
"Content-Type": "application/json",
};
var dataString = `{ "long_url": "${req.body.url}"}`;
const api_url = "https://api-ssl.bitly.com/v4/shorten";
var options = {
url: api_url,
method: "POST",
headers: headers,
body: dataString,
};
request(options, (error, body) => {
if (error) {
return res.status(404).send(error);
}
return res.render("index", { error: "", data: JSON.parse(body.body) });
});
my question is how can we use Axios instead of the request package because the request package is deprecated.
I tried but did not get success.
const token = process.env.BITLY_ACCESS_TOKEN;
let headers = {
Authorization: `Bearer ${token}`,
"Content-Type": "application/json",
};
var dataString = `{ "long_url": "${req.body.url}"}`;
const api_url = "https://api-ssl.bitly.com/v4/shorten";
const response = await axios.post(
api_url,
{ long_url: req.body.url },
{
headers: headers,
}
);
return res.render("index", { error: "", data: response });
I am getting errors like the body is not defined.
Please help me. Thank you!
const response = await axios.post(api_url, dataString, {
headers: headers,
});
console.log(response.data);
return res.render("index", { error: "", data: response.data });

Error when sending https request to ROBLOX API

I'm writing a simple API request to Roblox so I can retrieve the X-CSRF-TOKEN to do POST requests. The issue I'm facing is "Error: socket hang up".
I tried to just run the link in my browser and it displays a JSON table, but when I do the request through node.js it errors out.
const https = require("https")
const options = {
hostname: "groups.roblox.com",
path: "/v1/groups/5307563",
method: "GET",
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json',
'Cookie': '.ROBLOSECURITY=' + cookie
}
}
const request = https.request(options, res => {
res.on('data', data => {
console.log("data received")
})
});
request.on('error', error => {
console.log(error)
})
You need to end the request with request.end().
const https = require("https")
const options = {
hostname: "groups.roblox.com",
path: "/v1/groups/5307563",
method: "GET",
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json',
'Cookie': '.ROBLOSECURITY=' + cookie
}
}
const request = https.request(options, res => {
res.on('data', data => {
console.log("data received")
})
});
request.on('error', error => {
console.log(error)
})
request.end()

How to use bearer token for authorization for POST method in sync-request?

How can we use bearer token with POST method using npm sync-request? The sync-request resource page has the way to use authorization in GET request but not in POST request.
*******GET Request*******
var request = require('sync-request');
var res = request('GET', 'https://example.com', {
'headers': {
'user-agent': 'example-user-agent'
}
});
****POST Request*****
var request = require('sync-request');
var res = request('POST', 'https://example.com/create-user', {
json: { username: 'Name' }
});
Not sure why you would want to use sync-request which can cause timing issues but this should work with either sync-request or request
// *******GET Request*******
var request = require('sync-request');
var res = request('GET', 'https://example.com', {
'headers': {
'user-agent': 'example-user-agent',
'authorization', 'Bearer ' + authId
}
});
// ****POST Request*****
var request = require('sync-request');
var res = request('POST', 'https://example.com/create-user', {
'headers': {
'authorization', 'Bearer ' + authId
},
json: { username: 'Name' }
});
authId needs to be whatever your bearer token spoils be for your app.
I would suggest use of axis and example below:-
GET
import axios from "axios";
axios({
method: 'get',
url: url,
headers: {
'Content-Type': 'application/json'
}
}).then(function (response) {
console.log(response);
}).catch((err) => {
console.log(err)
));
POST
axios({
method: 'post',
url: url,
data: JSON.stringify({orders}),
headers: {
'Content-Type': 'application/json',
'Authorization': userObj.token
}
}).then(function (response) {
console.log(response)
});
Where ubserObj.token -
Bearer Token ex: Bearer ASDF#!##!ADFASDF!##!##
This will be on the server side settings.

NodeJS Patreon API account link

I'm trying to connect user accounts on my website to patreon. I keep getting an access_denied error message in response to step 3. I'm following this documentation.
My node server code looks like this:
socket.on("patreon_register",function(code,user){
var reqString = "api.patreon.com/oauth2/token?code="
+code
+"&grant_type=authorization_code&client_id="
+settings.patreon.Client_ID
+"&client_secret="
+settings.patreon.Client_Secret
+"&redirect_uri="
+"http%3A%2F%2Fwww.levisinger.com%2F%3Fpage%3Dpatreon_success",
req = querystring.stringify({
"code": code,
"grant_type": "authorization_code",
"client_id": settings.patreon.Client_ID,
"client_secret": settings.patreon.Client_Secret,
"redirect_uri": "http%3A%2F%2Fwww.levisinger.com%2F%3Fpage%3Dpatreon_success"
}),
post_options = {
host: 'api.patreon.com',
port: '80',
path: '/oauth2/token',
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Content-Length': Buffer.byteLength(req)
}
};
// Set up the request
console.log(req);
var post_req = http.request(post_options, function(res) {
res.setEncoding('utf8');
res.on('data', function (chunk) {
console.log(chunk);
if(
chunk.access_token &&
chunk.refresh_token &&
chunk.expires_in &&
chunk.scope &&
chunk.token_type
){
Auth.linkPatreon(user,chunk,function(err,res){
if(err){ socket.emit('patreon_register',false,res); }
else { socket.emit('patreon_register',true,res); }
});
}
});
});
// post the data
post_req.write(req);
post_req.end();
});
The req variable that's actually sent to the server looks like this (changed my codes to generic values of course)
code=MY_RESPONSE_CODE&grant_type=authorization_code&client_id=MY_CLIENT_ID&client_secret=MY_CLIENT_SECRET&redirect_uri=MY_RESPONSE_URI
Any ideas?
In the end, my server looks like this and is working:
socket.on("patreon_register",function(code,user){
var req = querystring.stringify({
code: code,
grant_type: "authorization_code",
client_id: settings.patreon.Client_ID,
client_secret: settings.patreon.Client_Secret,
redirect_uri: settings.patreon.redirect_uri
}),
post_options = {
host: 'api.patreon.com',
port: '80',
path: '/oauth2/token',
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Content-Length': Buffer.byteLength(req)
}
};
// Set up the request
console.log(req);
var post_req = http.request(post_options, function(res) {
res.setEncoding('utf8');
res.on('data', function (chunk) {
chunk = JSON.parse(chunk);
console.log(chunk);
if(!chunk["error"]){
console.log("Linking!");
Auth.linkPatreon(user,chunk,function(err,res){
if(err){ socket.emit('patreon_register',false,res); }
else { socket.emit('patreon_register',true,res); }
console.log("Linked!");
});
}
});
});

Resources