Functions in Nodejs - node.js

I am new to Nodejs and am trying to figure out why I cannot pass the returned value of my function into my function when I call it. Here is my code:
const SpotifyWebApi = require('spotify-web-api-node');
const http = require("http");
const request = require('request');
const querystring = require('querystring');
const { post } = require('request');
const express = require('express');
const { response } = require('express');
const https = require('follow-redirects').https;
//sets express server vars
const app = express()
const port = 8080
app.get('/', (req, res) => {
res.send('Server Connected')
})
app.listen(port, () => {
console.log(`Now serving on ${port} at ${process.env.URI} `)
})
require('dotenv').config();
//authenticate to SpotifyAPI
var spotifyApi = new SpotifyWebApi({
clientId: process.env.CLIENT_ID,
clientSecret: process.env.SECRET_ID,
redirectUri: process.env.URI,
});
const scope = 'user-read-private user-read-email ';
const authUrl = 'https://accounts.spotify.com/api/token?grant_type=client_credentials';
//Headers needed to auth to SpotifyAPI for Bearer token
const tokenHeaders = {
'Authorization': process.env.ACCESSTOKEN,
'Content-Type': 'application/x-www-form-urlencoded',
};
//spotify Auth Payload
const options = {
'method': 'POST',
'url': authUrl,
'headers': tokenHeaders
};
function accessTokenAuth(bearerToken){
request(options, (error, response) => {
if (error) throw new Error(error);
const accessTokenBody = response.body;
// console.log(accessTokenBody)
// console.log(request)
const obj = JSON.parse(accessTokenBody);
const bearerToken = ("Bearer " + obj.access_token); //add this bearerAuth part to a function to make it repeatable. Times out in 3600???
// console.log(bearerToken);
return bearerToken;
});
}
//Add first playlists request using the bearer token
accessTokenAuth(bearerToken);
In the function "accessTokenAuth" I create a series of calls that essentially posts data from the above dictionaries into a function that then sends the data to the URL to receive a token back. My question is this, at the bottom of the function when I return "bearerToken", how come I cannot pass "bearerToken" into the function when I call it on line 67. Also, when I comment out calling the function and just run the program it prints out the "bearerToken" when I console.log it in the function. Why is this possible? Aren't you not able to access the function unless it is called?
Thank you!

Related

discord Oauth2 access token undefined

So i am trying to create a discord bot dashboard and I am including a Discord Oauth2 to get User information. My Discord Oauth2 works, however after authorising, it redirects me to the homepage but the URL has token=undefined . The console does log "It works!". How do I fix the undefined access token?
http://localhost:3000/?token=undefined
var path = require('path');
const express = require('express');
const fetch = require('node-fetch');
const app = express();
require('dotenv').config();
const btoa = require('btoa');
const { catchAsync } = require('./utils.js')
const CLIENT_ID = process.env.CLIENT_ID;
const CLIENT_SECRET = process.env.CLIENT_SECRET;
const redirect = encodeURIComponent('http://localhost:3000/callback');
...
app.get('/login', (req, res) => {
res.redirect(`https://discord.com/api/oauth2/authorize?client_id=${CLIENT_ID}&redirect_uri=${redirect}&response_type=code&scope=identify%20email%20guilds`);
});
app.get('/callback', catchAsync(async (req, res) => {
if (!req.query.code) throw new Error('NoCodeProvided');
const code = req.query.code;
const creds = btoa(`${CLIENT_ID}:${CLIENT_SECRET}`);
const response = await fetch(`https://discordapp.com/api/oauth2/token?grant_type=authorization_code&code=${code}&redirect_uri=${redirect}`,
{
method: 'POST',
headers: {
Authorization: `Basic ${creds}`,
},
});
const json = await response.json();
console.log("it works!")
res.redirect(`/?token=${json.access_token}`);
}));
app.listen(3000)
There seemed to be a problem with how the callback link was set up, So I changed it to look like this and it works.
app.get('/callback', catchAsync(async (req, res) => {
const data = {
client_id: CLIENT_ID,
client_secret: CLIENT_SECRET,
grant_type: 'authorization_code',
redirect_uri: redirect,
code: req.query.code,
scope: ['identify', 'email', 'guilds'],
};
const response = await fetch('https://discord.com/api/oauth2/token', {
method: 'POST',
body: new URLSearchParams(data),
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
}
})
const json = await response.json();
const fetchDiscordUserInfo = await fetch('http://discordapp.com/api/users/#me', {
headers: {
Authorization: `Bearer ${json.access_token}`,
}
});
const userInfo = await fetchDiscordUserInfo.json();
res.redirect('http://localhost:3000/dashboard')
console.log(userInfo);

Why is server getting empty request.body from POST http request made with axios?

I'm trying to send a file (.obj file) via formdata to my node server, it appears that everything is fine until the controller of the endpoint on the server throws an error that seems to be like the formdata parser is receiving an empty formdata object, here is the error in question. Now, here's my code:
Fron-end (where the request is being executed):
const data = new FormData();
data.append('file', this.props.filesSubmit, this.props.filesSubmit.name);
for (var pair of data.entries()) {
console.log(pair[0] + ', ' + pair[1]);
}
await axios
.post(
'https://hushpuppys-3d-hub-api.herokuapp.com/api/v1/modelfiles/',
data,
{
headers: {
'Content-Type': undefined,
},
}
)
.then((res) => {
console.log('File Upload Successful! Res: ', res);
})
.catch((err) => {
console.log(err);
});
Back-end endpoint Controller (Where request is received):
const AWS = require('aws-sdk');
const fs = require('fs');
const fileType = require('file-type');
const bluebird = require('bluebird');
const multiparty = require('multiparty');
// Keys Configuration to Access AWS
AWS.config.update({
accessKeyId: '[I erased this]',
secretAccessKey: '[I erased this]',
});
// Configuring AWS to work with promises
AWS.config.setPromisesDependency(bluebird);
// Creating S3 instance
const s3 = new AWS.S3();
// abstracts function to upload a file returning a promise
const uploadFile = (buffer, name, type) => {
const params = {
ACL: 'public-read',
Body: buffer,
Bucket: '[I erased this]',
ContentType: type.mime,
Key: `${name}.${type.ext}`,
};
return s3.upload(params).promise();
};
exports.fileUploaderController = (req, res) => {
const form = new multiparty.Form();
form.parse(req.body, async (error, fields, files) => {
if (error) throw new Error(error);
try {
const path = files.file[0].path;
const buffer = fs.readFileSync(path);
const type = fileType(buffer);
const timestamp = Date.now().toString();
const fileName = `bucketFolder/${timestamp}-lg`;
const data = await uploadFile(buffer, fileName, type);
return res.status(200).send(data);
} catch (error) {
return res.status(400).send(error);
}
});
};
I want to also add the code of my app.js where other middlewares manipulate the body, maybe that's also relevant to solve the problem:
const express = require('express');
const modelRouter = require('./routes/modelRoutes');
const modelFilesRouter = require('./routes/modelFilesRoutes');
const cors = require('cors');
const app = express();
// MIDDLEWARES
app.use(cors());
app.use(express.json({ limit: '50mb' }));
app.use(express.urlencoded({ limit: '50mb' }));
// ROUTES
app.use('/api/v1/models', modelRouter);
app.use('/api/v1/modelfiles', modelFilesRouter);
module.exports = app;
Ok, I got this problem solved a few minutes ago. I was basically passing a wrong parameter in the form.parse() method in the fileUploaderController controller from the Controller file, the method form.parse() needs the whole req variable to be passed as a parameter, not the body of the request (req.body) as I did in the code I posted with the question.

Options.method property must be of type string

I am attempting to authenticate to the spotifyApi using Node.js and Express. The server starts fine and is not a problem. However I am getting this error:
SERVING ON PORT 8000
Now serving on 8080 at http://localhost:8080
/home/aroe/projects/projectPerfect/spotifyApi.js:55
if (error) throw new Error(error);
^
Error: TypeError [ERR_INVALID_ARG_TYPE]: The "options.method" property must be of type string. Received type function ([Function])
at Request._callback (/home/aroe/projects/projectPerfect/spotifyApi.js:55:20)
at self.callback (/home/aroe/projects/projectPerfect/node_modules/request/request.js:185:22)
at Request.emit (events.js:310:20)
at Request.start (/home/aroe/projects/projectPerfect/node_modules/request/request.js:753:10)
at Request.end (/home/aroe/projects/projectPerfect/node_modules/request/request.js:1505:10)
at end (/home/aroe/projects/projectPerfect/node_modules/request/request.js:564:14)
at Immediate.<anonymous> (/home/aroe/projects/projectPerfect/node_modules/request/request.js:578:7)
Here is my code:
const SpotifyWebApi = require('spotify-web-api-node');
const http = require("http");
const request = require('request');
const myserver = require('./server');
const querystring = require('querystring');
const { post } = require('request');
const express = require('express')
const https = require('follow-redirects').https;
//sets express server vars
const app = express()
const port = 8080
app.get('/', (req, res) => {
res.send('Server Connected')
})
app.listen(port, () => {
console.log(`Now serving on ${port} at ${process.env.URI} `)
})
require('dotenv').config();
//authenticate to SpotifyAPI
var spotifyApi = new SpotifyWebApi({
clientId: process.env.CLIENT_ID,
clientSecret: process.env.SECRET_ID,
redirectUri: process.env.URI,
});
const scope = 'user-read-private user-read-email ';
const authUrl = 'https://accounts.spotify.com/api/token';
//Headers needed to auth to SpotifyAPI for Bearer token
const tokenHeaders = {
'Authorization': process.env.ACCESSTOKEN,
'Content-Type': 'application/x-www-form-urlencoded'
};
//spotify Auth Payload
const options = {
'method': post,
'url': authUrl,
'headers': tokenHeaders
};
request(options, (error, response) => {
if (error) throw new Error(error);
console.log(response.body);
});
In the function in question I am attempting to post my payload back to the APIURL. I got the bottom part of this code directly from Postman.

invalid_request post to access Token

I have problem with post request authentification while trying to run the code I get error invalide request does anyone know how I could solve this problem, I get this error { error: 'invalid_request' }
const express = require('express');
const fetch = require('node-fetch');
const btoa = require('btoa');
const { catchAsync } = require('./utils');
const router = express.Router();
const CLIENT_ID = 'CLIENT_ID ';
const CLIENT_SECRET = 'CLIENT_SECRET';
const creds = btoa(`${CLIENT_ID}:${CLIENT_SECRET}`);
const redirect = encodeURIComponent('http://localhost:50451/callback');
router.get('/login', (req, res) => {
res.redirect('https://flow.polar.com/oauth2/authorization?response_type=code&client_id=client_id');
});
router.get('/list', catchAsync(async (req, res) => {
if (!req.query.code) throw new Error('NoCodeProvided');
const code = req.query.code;
const creds = btoa(`${CLIENT_ID}:${CLIENT_SECRET}`);
fetch('https://polarremote.com/v2/oauth2/token', {
method: 'POST',
data : {
'grant_type' : 'authorization_code',
'redirect_uri' : redirect,
'code' : code
},
headers : {
'Authorization':`Basic ${creds}`,
'Content-Type':'application/x-www-form-urlencoded',
'Accept':' application/json;charset=UTF-8'
}
})
.then(function(response) {
return response.json();
console.log(response.json());
}).then(function(body) {
console.log(body);
res.send('POST');
});
})

Make voice call using node js

I am using Both Java web server and node js(for chat)
Now I want to make voice call using Twilio`
I wrote code like this
var fs = require('fs');
var sslOptions = {};
var path = require('path');
var express = require('express');
var app = express();
var server = require('https').createServer(sslOptions, app);
const EventEmitter = require('events');
const myEE = new EventEmitter();
server.on("request", function (req, res) {
res.end("this is the response");
});
server.listen('8090', function(){
console.log("Secure Express server listening on port 8090");
});
var accountSid = 'AC***************************';
var authToken = "******************************";
var client = require('twilio')(accountSid, authToken);
var morgan = require('morgan');
var bodyParser = require('body-parser');
var twilio = require('twilio');
var VoiceResponse = twilio.twiml.VoiceResponse;
module.exports = server;
app.use(express.static(path.join(process.cwd(), 'public')));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: true,
}));
app.use(morgan('combined'));
app.get('/', function(request, response) {
response.render('index');
});
app.post('/call', function(request, response) {
var salesNumber = request.body.salesNumber;
var url = 'http://' + request.headers.host + '/outbound/' + encodeURIComponent(salesNumber);
var options = {
to: '+91*******',
from: '+17******',
url: url,
};
client.calls.create(options)
.then((message) => {
response.send({
message: 'Thank you! We will be calling you shortly.',
});
})
.catch((error) => {
console.log('errot');
// console.log(error);
response.status(500).send('error');
});
});
app.post('/outbound/:salesNumber', function(request, response) {
var salesNumber = request.params.salesNumber;
var twimlResponse = new VoiceResponse();
twimlResponse.say('Thanks for contacting our sales department. Our ' +
'next available representative will take your call. ',
{ voice: 'alice' });
twimlResponse.dial(salesNumber);
response.send(twimlResponse.toString());
});
I am trying to make an ajax call from one of my javascript files to an express route
$.ajax({ url: '/call',
method: 'POST',
dataType: 'application/json',
processData: false,
data: {
phoneNumber: '+91*******',
salesNumber:'+17******** '
}
}).done(function(data) {
// The JSON sent back from the server will contain a success message
alert(data.message);
}).fail(function(error) {
//alert('errot');
alert(JSON.stringify(error));
});
when I execute this ajax call
it's looking for Java server and return 404 error
How can I solve this issue
Anyone, please help me to solve this issue

Resources