I'm trying to create an app with the Spotify API, but can't seem to get it to work. The error I'm getting is that 'request' is undefined and I've replaced it with JQuery too and that doesn't work either. Can anyone tell me why I might be getting that error and how to fix it? Should I be running it inside node.js in cmd?
var client_id = '?';
var client_secret = '?';
var authOptions = {
url: 'https://accounts.spotify.com/api/token',
headers: {
'Authorization': 'Basic ' + (new Buffer(client_id + ':' + client_secret).toString('base64'))
},
form: {
grant_type: 'client_credentials'
},
json: true
};
request.post(authOptions, function(error, response, body) {
if (!error && response.statusCode === 200) {
var token = body.access_token;
}
else {
console.log(JSON.stringify(error))
}
});
The spotify documentation is out of date, as request is deprecated, and should no longer be used.
Instead, you can make a request with built-in Node.js libraries, as mentioned in the documentation.
It should be run with node.js, i.e. node <filename>
const https = require('https')
const client_id = 'CLIENT_ID'
const client_secret = 'CLIENT_SECRET'
const reqBody = JSON.stringify({
grant_type: 'client_credentials'
})
const authOptions = {
hostname: 'accounts.spotify.com',
port: 443,
path: '/api/token',
method: 'POST',
headers: {
'Authorization': 'Basic ' + (new Buffer.from(client_id + ':' + client_secret).toString('base64')),
'Content-Type': 'application/json',
'Content-Length': reqBody.length
}
}
const req = https.request(authOptions, res => {
console.log(`statusCode: ${res.statusCode}`)
res.on('data', d => {
process.stdout.write(d)
})
})
req.write(reqBody);
req.end();
Related
I am using the Spotify Web API to get my access token. It is working perfectly.
In my frontend application, I would like to use axios to get the access token.
How can I do that?
Because my axios.get method is not working.
Here I am getting the access token:
app.get('/callback', function(req, res) {
your application requests refresh and access tokens after checking the state parameter
var code = req.query.code || null;
var state = req.query.state || null;
var storedState = req.cookies ? req.cookies[stateKey] : null;
console.log('reqcookie', req.cookie)
if (state === null || state !== storedState) {
res.redirect('/#' +
querystring.stringify({
error: 'state_mismatch'
})
);
} else {
res.clearCookie(stateKey);
var authOptions = {
url: 'https://accounts.spotify.com/api/token',
form: {
code: code,
redirect_uri: redirect_uri,
grant_type: 'authorization_code'
},
headers: {
'Authorization': 'Basic ' + (new Buffer(client_id + ':'
+
client_secret).toString('base64'))
},
json: true
};
request.post(authOptions, function(error, response, body) {
if (!error && response.statusCode === 200) {
var access_token = body.access_token,
refresh_token = body.refresh_token;
console.log('accestoken ',access_token)
console.log('body', body)
var options = {
url: 'https://api.spotify.com/v1/me',
headers: { 'Authorization': 'Bearer ' + access_token
},
json: true
};
Use the access token to access the Spotify Web API
request.get(options, function(error, response, body) {
console.log('hi')
console.log(body)
});
...not important code
console.log('Listening on 8888');
app.listen(8888);
That's how I use axios in my frontend application to get the data and later the access token.
But it is currently not working
axios({
method: 'get',
url: 'http://localhost:8000/callback'
}).then(data => console.log(data))
.catch(err => console.log(err))
I'm trying to get data from API, I get it with Node & Postman, but I can't make it work on the browser.
I get 403 Forbidden (anonymous).
Is it my problem or maybe something that's supposed to be enabled in the server?
var urlAPI = "http://example.com/api/v1/";
var uname = 'username';
var pass = 'password';
var headers = new Headers();
headers.set('Authorization', 'Basic ' + btoa(uname + ':' + pass));
fetch(urlAPI, {
mode: 'no-cors',
credentials: 'include',
headers: headers
})
.then(function () {
console.log("ok");
}).catch(function (err) {
console.log("error: " + err);
});
I can make this work with axios but as I want to do this with default http module for some reasons
Here is the code
var express = require("express");
const http = require('https');
var app = express();
app.listen(3000, function () {
var username = 'username';
var password = 'password';
var auth = 'Basic ' + Buffer.from(username + ':' + password).toString('base64');
const data = JSON.stringify({
campaign_id: 'all',
start_date: '01/01/2010',
end_date: '05/31/2030',
return_type: 'caller_view',
criteria: {
phone: 98855964562
}
});
var hostName = "https://staging.crm.com";
var path = "/api/v1/caller_find";
const options = {
hostName: hostName,
path: path,
port: 3000,
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': auth,
'Content-Length': data.length
}
};
const req = http.request(options, (res) => {
console.log('response is ' + res);
});
req.on('error', (error) => {
console.log('error is ' + error);
});
});
But it is throwing exception
connect ECONNREFUSED 127.0.0.1:443
It seems like you're providing the wrong options object (perhaps copied over from axios). The Node.js HTTP module takes host or hostname in options, while you're providing hostName.
Reference: https://nodejs.org/api/http.html#http_http_request_options_callback
I'm not entirely sure what you're trying to do. Any reason why you need your application to listen? I'm assuming the application you're posting to is hosted somewhere else, as you're attempting to listen to port 3000 while also making the request to an application on port 3000. If each application is on a different host, this should be fine. Nonetheless, you've at least got 3 issues here.
1) Your options object is incorrect. You're using hostName when it should be hostname. This is why you get the ECONNREFUSED 127.0.0.1:443 error; the options object for the https.request() method defaults hostname to localhost and port to 443.
2) Also, you never write your data object contents to the request stream.
3) Finally, you should listen to the data event to get the response back and write it to the console. I've updated your code as shown below:
var express = require("express");
const http = require('https');
var app = express();
app.listen(3000, function () {
var username = 'username';
var password = 'password';
var auth = 'Basic ' + Buffer.from(username + ':' + password).toString('base64');
const data = JSON.stringify({
campaign_id: 'all',
start_date: '01/01/2010',
end_date: '05/31/2030',
return_type: 'caller_view',
criteria: {
phone: 98855964562
}
});
var hostName = "https://staging.crm.com";
var path = "/api/v1/caller_find";
const options = {
hostname: hostName,
path: path,
port: 3000,
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': auth,
'Content-Length': Buffer.byteLength(data)
}
};
const req = http.request(options, (res) => {
console.log(`statusCode: ${res.statusCode}`)
res.on('data', (chunk) => {
console.log(`BODY: ${chunk}`);
});
res.on('end', () => {
console.log('No more data in response.');
});
});
req.on('error', (error) => {
console.log('error is ' + error);
});
req.write(data);
req.end();
});
You cannot move your express application to AWS Lambda as is. There are tools such as claudia which can help you move the app to lambda and api gateway.
In your case, you can modify your code AWS Lambda as below
const http = require('https');
exports.myHandler = function (event, context, callback) {
var username = 'username';
var password = 'password';
var auth = 'Basic ' + Buffer.from(username + ':' + password).toString('base64');
const data = JSON.stringify({
campaign_id: 'all',
start_date: '01/01/2010',
end_date: '05/31/2030',
return_type: 'caller_view',
criteria: {
phone: 98855964562
}
});
var hostName = "https://staging.crm.com";
var path = "/api/v1/caller_find";
const options = {
hostName: hostName,
path: path,
port: 3000,
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': auth,
'Content-Length': data.length
}
};
const req = http.request(options, (res) => {
console.log('response is ' + res);
callback(null, res);
});
req.on('error', (error) => {
console.log('error is ' + error);
callback(error);
});
}
You have to invoke your lambda via API Gateway or via other AWS resources such as Alexa Skill Kit etc.
EDIT
You may try passing auth options as specified # https://github.com/request/request/blob/master/README.md#http-authentication
I am trying to use the tiny.cc REST API from Node, but seem to be hitting an issue since the Server always responds with a message 'Missing input parameters'.
var message = JSON.stringify({
"urls": [
{
"long_url": "http://example.com",
}
]
});
var https_options = {
host: 'tinycc.com',
path: '/tiny/api/3/urls/',
port: 443,
method: 'POST',
headers: {
'Authorization': 'Basic XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX',
'Content-Length': message.length
}
}
var req = https.request(https_options,res => {
var msg = '';
res.on('data',d => msg += d);
res.on('end',() => {
console.log('end',JSON.parse(msg));
});
});
req.on('error',e => console.log('tinyURL error',e));
req.write(message);
req.end();
The response is always
{
error: {
code: 1305,
message: 'Missing input parameters',
details: ''
},
version: '3.1'
}
I don't know which library are you using for making the API call, but I think you will be better using request and including your payload as the body on your post request rather than using the more manual method of writing to the request.
var message = {
"urls": [
{
"long_url": "http://example.com",
}
]
};
var options = {
host: 'tinycc.com',
path: '/tiny/api/3/urls/',
port: 443,
method: 'POST',
body: message,
json: true,
headers: {
'Authorization': 'Basic XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX',
'Content-Length': message.length,
"Content-Type": "application/json"
}
}
request(options, console.log)
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);
});