Extracting values from API data in node.js - node.js

Thank you for your time.
I'm trying to use OAuth2 in discord, but I'm having a hard time figuring out how to retrieve the username.
Can someone please tell me how to do it?
code
const fetch = require('node-fetch');
const express = require('express');
const app = express();
app.get('/', async ({ query }, response) => {
const { code } = query;
if (code) {
try {
const oauthResult = await fetch('https://discord.com/api/oauth2/token', {
method: 'POST',
body: new URLSearchParams({
client_id: process.env['ci'],
client_secret: process.env['cs'],
code,
grant_type: 'authorization_code',
redirect_uri: `https://oauth.aiueominato1111.repl.co`,
scope: 'identify',
}),
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
});
const oauthData = await oauthResult.json();
const userResult = await fetch('https://discord.com/api/users/#me', {
headers: {
authorization: `${oauthData.token_type} ${oauthData.access_token}`,
},
});
console.log( await userResult.json());
} catch (error) {
// NOTE: An unauthorized token will not throw an error;
// it will return a 401 Unauthorized response in the try block above
console.error(error);
}
}
return response.sendFile('index.html', { root: '.' });
});
app.listen(port, () => console.log(`App listening at http://localhost:${port}`));
thank you

You already have the JSON data (from await userResult.json()) with it you can either get the property from the object or destructure it.
Getting property
const user = await userResult.json();
const username = user.username
Destructuring
const { username, id } = await userResult.json()
You can find out more about what properties you can extract from the Discord documentation

Related

I am getting weird data as a response

I am trying to get some details of mail that I have sended using google-api. I am using messageId that I have received after sending email. I am expection the data to be in json format.
Here is the Nodejs code for reading sended mail:
app.post("/readMail", async (req, res)=>{
let messageId = req.body.messageId;
try {
const oAuth2Client = new google.auth.OAuth2(
properties.GOOGLE_CLIENT_ID,
properties.GOOGLE_CLIENT_SECRET,
);
oAuth2Client.setCredentials({ refresh_token: properties.REFRESH_TOKEN });
const { token } = await oAuth2Client.getAccessToken();
const generateConfig = (url, accessToken) => {
return {
method: "get",
url: url,
headers: {
Authorization: `Bearer ${accessToken} `,
"Content-type": "application/json",
},
};
};
const url = `https://gmail.googleapis.com/gmail/v1/users/Abhisek721#gmail.com/messages/${messageId}`;
const config = generateConfig(url, token);
const response = await axios(config);
let data = await response.data;
res.json(data);
} catch (error) {
res.send(error);
}
})
And This the response:
"\u001f\ufffd\b\u0000\u0000\u0000\u0000\u0000\u0002\ufffd\ufffdUmo\ufffd:\u0014\ufffd\ufffd_a\ufffdu\ufffds\u0012^\ufffdN\ufffd\u0006\t/a\ufffd2\ufffd\ufffd\ufffdީr\u0012\ufffd\u0018\ufffd8rLB6\ufffd\ufffd_'P\ufffdݱ\ufffd^]\ufffd\ufffd\ufffd\ufffd\ufffd=\ufffd\ufffd\ufffd\u000e\ufffd\n\ufffd*\ufffd\ufffd\ufffd\ufffdu\ufffd:\\75\ufffd]C\ufffdrU\ufffdD\ufffd1\ufffdW4(r0\ufffd\ufffdDj\ufffd%\ufffd\ufffdd\ufffd\u0019\ufffd*\ufffd\ufffdR\ufffdD$\ufffd\ufffd(\u0000:!\"\u0014\ufffd8r\ufffd\ufffd\ufffd!\ufffd8\u0004$Nv!"
I was expecting to get something like json data.

Axios POST request to Twillio returns with an Authentication Error?

in Node.js, I am trying to send a POST request with Axios to Twilio and send an SMS message to my phone. But I am getting an 'error: Authentication Error - No credentials provided ? Here is the code:
const body = {
'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8',
Body: 'hi from vsc',
To: toNumber,
From: fromNumber,
};
const headers = {
'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8',
Authorization: `Basic ${accountSID}:${authToken}`,
};
exports.axios = () => axios.post(`https://api.twilio.com/2010-04-01/Accounts/${accountSID}/Messages.json`, body, headers).then((res) => {
console.log(res, 'res');
}).catch((err) => {
console.log(err);
});
I also tried to use the same parameters with POSTMAN and the POST request is successful. I also tried to encode my authorization username and password to Base 64, but with no success.
I wrote to Twilio customer help but haven`t received any replies yet.
Axios makes an auth option available that takes an object with username and password options. You can use this with the username set to your account SID and password set to your auth token.
The headers object should be sent as the headers parameter of a config object in the third parameter to axios.post. Like so:
const params = new URLSearchParams();
params.append('Body','Hello from vcs');
params.append('To',toNumber);
params.append('From',fromNumber);
const headers = {
'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8',
};
exports.axios = () => axios.post(
`https://api.twilio.com/2010-04-01/Accounts/${accountSID}/Messages.json`,
params,
{
headers,
auth: {
username: accountSID,
password: authToken
}
}
}).then((res) => {
console.log(res, 'res');
}).catch((err) => {
console.log(err);
});
Headers is actually a field of config, try something like this:
const config = {
headers: {
'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8',
Authorization: `Basic ${accountSID}:${authToken}`,
}
}
axios.post(URL, data, config).then(...)
Or this (general example calling a Twilio endpoint)
const axios = require('axios');
const roomSID = 'RM1...';
const participantSID = 'PA8...';
const ACCOUNT_SID = process.env.ACCOUNT_SID;
const AUTH_TOKEN = process.env.AUTH_TOKEN;
const URL = "https://insights.twilio.com/v1/Video/Rooms/"+roomSID+"/Participants/"+participantSID;
axios({
method: 'get',
url: URL,
auth: {
username: ACCOUNT_SID,
password: AUTH_TOKEN
}
})
.then((response) => {
console.log(response.data);
})
.catch((error) => {
console.log(error);
});
Working code:
const params = new URLSearchParams();
params.append('Body','Hello from vcs');
params.append('To',toNumber);
params.append('From',fromNumber);
exports.axios = () => axios.post(
`https://api.twilio.com/2010-04-01/Accounts/${accountSID}/Messages.json`,
params,
{
auth: {
username: accountSID,
password: authToken,
},
},
).then((res) => {
console.log(res, 'res');
}).catch((err) => {
console.log(err);
});
The previous solutions did not work for me. I encountered either the Can't find variable: btoa error or A 'To' phone number is required..
Using qs worked for me:
import qs from 'qs';
import axios from 'axios';
const TWILIO_ACCOUNT_SID = ""
const TWILIO_AUTH_TOKEN = ""
const FROM = ""
const TO = ""
const sendText = async (message: string) => {
try {
const result = await axios.post(
`https://api.twilio.com/2010-04-01/Accounts/${TWILIO_ACCOUNT_SID}/Messages.json`,
qs.stringify({
Body: message,
To: TO,
From: FROM,
}),
{
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
auth: {
username: TWILIO_ACCOUNT_SID,
password: TWILIO_AUTH_TOKEN,
},
},
);
console.log({result});
} catch (e) {
console.log({e});
console.log({e: e.response?.data});
}
};

Request form URL encoded within a request

I'm trying to make a request form_url_encoded when requesting a request, but it's giving me an error on the console that is already on port 3000, it's giving some error but not finding it, because if I leave the default as in the doc, it runs normal and opens at the door. I get:
Error: connect ECONNREFUSED
const express = require("express");
const router = express.Router();
const axios = require("axios");
const qs = require("qs");
const requestBody = {
refresh_token:
"1000.51355b1f8f5a8176026525670b5bbf3e.93c56a6bd3cb4589bd65b334810848cf",
client_id: "1000.KS2QNMSAQIMS74YBGZROSXD8QD3GWO",
client_secret: "06abfcc05409c430fb15252d47e8d9fe03a3582cbc",
rant_type: "refresh_token",
};
const config = {
headers: {
"Content-Type": "application/x-www-form-urlencoded",
},
};
const config2 = {
headers: {
"Content-Type": "application/json",
},
};
axios
.post(
"/crm7/sell_order",
{ test: "test" },
config2
)
.then((res) => {
console.log(res);
return axios.post("https://accounts.blue.com/oauth/v2/token", qs.stringify(requestBody), config);
})
.then((res) => {
console.log(res)
})
.catch((err) => {
console.log(err)
});
module.exports = router;

Twitter search API getting errors

I am trying to collect twitter search results.
I am using twitter search API with Nodejs.
Started with "quick start" given in twitter api site https://developer.twitter.com/en/docs/labs/recent-search/quick-start, but I am keeping get errors from my request.
this is my code:
const https = require('https');
const request = require('request');
const util = require('util');
const get = util.promisify(request.get);
const post = util.promisify(request.post);
const consumer_key = 'xxxxxxx'; // Add your API key here
const consumer_secret = 'xxxxxx'; // Add your API secret key here
const bearerTokenURL = new URL('https://api.twitter.com/oauth2/token');
const searchURL = new URL('https://api.twitter.com/labs/2/tweets/search');
async function bearerToken (auth) {
const requestConfig = {
url: bearerTokenURL,
auth: {
user: consumer_key,
pass: consumer_secret,
},
form: {
grant_type: 'client_credentials',
},
};
const response = await post(requestConfig);
return JSON.parse(response.body).access_token;
}
(async () => {
let token;
const query = 'obama';
const maxResults = 10;
try {
// Exchange your credentials for a Bearer token
token = await bearerToken({consumer_key, consumer_secret});
} catch (e) {
console.error(`Could not generate a Bearer token. Please check that your credentials are correct and that the Filtered Stream preview is enabled in your Labs dashboard. (${e})`);
process.exit(-1);
}
const requestConfig = {
url: searchURL,
qs: {
query: query,
max_results: maxResults,
format: 'compact',
},
auth: {
bearer: token,
},
headers: {
'User-Agent': 'LabsRecentSearchQuickStartJS',
},
json: true,
};
try {
const res = await get(requestConfig);
console.log(res.statusCode);
console.log(res);
if (res.statusCode !== 200) {
throw new Error(res.json);
return;
}
console.log(res.json);
} catch (e) {
console.error(`Could not get search results. An error occurred: ${e}`);
process.exit(-1);
}
})();
my error:
body: {
errors: [ [Object] ],
title: 'Invalid Request',
detail: 'One or more parameters to your request was invalid.',
type: 'https://api.twitter.com/labs/2/problems/invalid-request' }, [Symbol(kCapture)]: false } Could not get search results. An
error occurred: Error
There's a bug in this script which we need to fix. If you remove the line format: 'compact', then this will work - that parameter is no longer valid in Labs v2.

Fetch API failed to Fetch during authentication, alongside CORS error

I have a button that lauches a fetch to my API that uses KOA and JWT. The javascript for the fetch initiated on click is:
<script>
function loginButton(user, pass) {
fetch('http://localhost:5454/api/login', {
method: "post",
headers: {
'Content-Type': "application/json"
},
body: JSON.stringify({
username: user,
password: pass
})
})
.then( (response) => {
console.log("Success")
})
.catch(e => console.log(e));
}
</script>
The code for my Authentication is:
router.post(`${BASE_URL}/login`, async (ctx) => {
const reqUsername = ctx.request.body.username
const reqPassword = ctx.request.body.password
const unauthorized = (ctx) => {
ctx.status = 401
ctx.body = {
error: 'Invalid username or password'
}
}
let attemptingUser
try {
attemptingUser = await Employee.findOne({ where: { username: reqUsername }})
if (attemptingUser != null && attemptingUser.password === reqPassword) {
ctx.status = 200
ctx.body = {
username: attemptingUser.username,
given_name: attemptingUser.given_name,
role: attemptingUser.role,
created_at: attemptingUser.createdAt,
updated_at: attemptingUser.updatedAt,
}
const token = jwt.sign({ username: attemptingUser.username, role: attemptingUser.role }, SECRET)
ctx.set("X-Auth", token)
} else {
unauthorized(ctx)
}
} catch(err) {
console.error(err)
console.error(`Failed to find username: ${reqUsername}`)
unauthorized(ctx)
}
})
The code for my KOA initiation is:
require('dotenv').config()
const Koa = require('koa')
const Router = require('koa-router')
const bodyParser = require('koa-bodyparser')
const baseRoutes = require('./routes')
const cors = require('#koa/cors');
const PORT = process.env.PORT || 8080
const app = new Koa()
app.use(bodyParser())
app.use(baseRoutes.routes())
app.use(cors());
app.listen(PORT, () => {
console.log(`Server listening on ${PORT}`)
})
Im using Port 8080 for my http-server and port 5454 for my npm server. I am getting a Failed to Fetch in the catch of the Fetch, as well as a CORS error related to not having a Access-Control-Allow-Origin header in the response header. I've tried a couple things and am ready to have a new set of eyes look at it, any tips?
Edit: I am successfully receiving the token in the X-Auth header, but for some reason it’s still throwing errors and I’d like to get them resolved before it spirals out of control.

Resources