const request = {
headers: {
"Accept": "application",
"Content-Type": "application/json",
},
method: "GET",
url: '',
} as any;
const result = await axios(request);
result.data.data.map(async (ad: any) => {
const request2 = {
headers: {
"Accept": "application",
"Content-Type": "application/json",
},
method: "GET",
url: '',
} as any;
const result2 = await axios(request2);
ad.preview = result2.data.data[0].body;
})
return result.data.data;
preview key is not getting appended
The problem is that the return-statement runs before the async map-callbacks have finished. Since you're not actually returning anything inside your map, it does not make a lot of sense to use it though. Just use a for..of loop:
const result = await axios(request);
for (const ad of result.data.data) {
const request2 = {...}
const result2 = await axios(request2);
ad.preview = result2.data.data[0].body;
}
return result.data.data;
So what happens is I am creating a discord bot that access the routes from express and it works if I keep it on a certain server, but if I try to access express on a different server while the server is on I get
Restarting the server removes the "assignments is not a function" So this only works when I try to access these routes endpoints from a completely different server. More information, If I try to do curl requests to these endpoints with different channel or guild id information, I also get that error. So I am assuming thats where a lot of the problem is coming from. I don't know why different information throws off the function.
index.js
import express, { json, query, request, response } from 'express';
import { assignments , announcements , discussions} from "./Fetch/fetchCalls.js";
var app = express();
app.use(express.json());
const PORT = 8080;
app.listen(PORT);
var guild;
var channel;
app.all('/assignments',(request) => {assignments(guild = request.body.guild, channel = request.body.channel);});
app.all('/discussions',(request) => {discussions(guild = request.body.guild,channel = request.body.channel); });
app.all('/announcements', (request) => {announcements(guild = request.body.guild,channel = request.body.channel);});
fetchCalls.js
import fetch from 'node-fetch';
import { createRequire } from "module";
import { getRecord, updateChannelID } from './dbUtil.js';
import { clearData } from './clear.js';
const require = createRequire(import.meta.url);
const config = require("../Canvas Bot/Source/Data/config.json")
var obj;
var course;
var url;
var access_token;
var guildid;
var channelid;
export function discussions(guild,channel) {
guildid = guild;
channelid = channel;
discussionsFunc();
async function discussionsFunc(){
try {
updateChannelID(guildid,channelid);
await getRecord({ guild_id : `${guildid}`}, getFetchData);
const res1 = await fetch(url + `courses/${course}/discussion_topics?scope=unlocked`, {
method: "GET",
headers: {
Authorization: `Bearer ${access_token}`,
"Content-Type": "application/json",
},
});
const apiData = await res1.json();
for(discussions of apiData){
const string = ["**TOPIC: "+discussions.title +"**", discussions.message + "\n"];
const res2 = await fetch(
`https://discordapp.com/api/channels/${channelid}/messages`,
{
method: "POST",
headers: {
"Authorization": `Bot ${config.TOKEN}`,
Accept: "application/json",
"Content-Type": "application/json",
},
"Connection": "close",
body: JSON.stringify({
content: string.join('\n').replace(/(<([^>]+)>)/gi, "")
}),
}
);
const apiResponse = await res2.json();
}
} catch (err) {
console.log(err);
}
}
clearData();
};
export function announcements(guild,channel) {
guildid = guild;
channelid = channel;
announcementsFunc();
async function announcementsFunc(){
updateChannelID(guildid,channelid);
try {
await getRecord({ guild_id : `${guildid}`}, getFetchData);
const res1 = await fetch(url + `/announcements?context_codes[]=${obj}&latest_only=true`, {
method: "GET",
headers: {
Authorization: `Bearer ${access_token}` ,
"Content-Type": "application/json",
},
});
const apiData = await res1.json();
console.log(apiData);
for( announcements of apiData){
const string = [`\`\`\`${announcements.title}\n`, `${announcements.message}\n\`\`\``];
const res2 = await fetch(
`https://discordapp.com/api/channels/${channelid}/messages`,
{
method: "POST",
headers: {
"Authorization": `Bot ${config.TOKEN}`,
Accept: "application/json",
"Content-Type": "application/json",
},
"Connection": "close",
body: JSON.stringify({
content: string.join('\n').replace(/(<([^>]+)>)/gi, "")
}),
}
);
const apiResponse = await res2.json();
console.log(apiResponse);
}
} catch (err) {
console.log(err);
}
}
clearData();
}
export function assignments(guild, channel) {
guildid = guild;
channelid = channel;
assignmentsFunc();
async function assignmentsFunc(){
updateChannelID(guildid,channelid);
try {
await getRecord({guild_id : `${guildid}`}, getFetchData);
const res1 = await fetch(url + `/courses/${course}/assignments?order_by=due_at`, {
method: "GET",
headers: {
Authorization: `Bearer ${access_token}`,
"Content-Type": "application/json",
},
});
const apiData = await res1.json();
console.log(apiData);
var size = apiData.length-1;
for( assignments of apiData){
const string = [`\`\`\`Name: ${assignments.name}`, `Description:\n ${assignments.description}`,`Due Date: ${assignments.due_at}\n\`\`\``];
const res2 = await fetch(
`https://discordapp.com/api/channels/${channelid}/messages`,
{
method: "POST",
headers: {
"Authorization": `Bot ${config.TOKEN}`,
Accept: "application/json",
"Content-Type": "application/json",
},
"Connection": "close",
body: JSON.stringify({
content: string.join('\n').replace(/(<([^>]+)>)/gi, "")
}),
}
);
const apiResponse = await res2.json();
console.log(apiResponse);
}
} catch (err) {
console.log(err);
}
}
clearData();
}
function getFetchData(document) {
obj = 'course_' + document._courseid;
course = document._courseid;
course1 = "_" + course;
url = 'https://' + document.prefix + '.instructure.com/api/v1/';
access_token = document.access_token;
console.log('obj = ' + obj + '\ncourse = ' + course + '\nurl = ' + url + '\naccess_token = ' + access_token);
}
and if necessary
dbUtil.js
import { MongoClient } from 'mongodb';
const uri = 'cluser uri';
const client = new MongoClient(uri)
export async function updateChannelID(guildids, channelids) {
try{
await client.connect();
// db name and collection
const database = client.db("Users");
const docs = database.collection("user_info");
var query = {guild_id: `${guildids}`};
var insert = {$set: {channel_id: `${channelids}`}};
// find the first record matching the given query
docs.updateOne(query,insert);
}
catch(error){
console.log(error);
}
}
The problem lies in the fetchCall.js file. First of all, you are exporting things in the wrong manner. If you are not using tools like babel, syntax export function ... is incorrect, you have to use module.exports to export things from a Node.js module.
So you can change your file in the following manner, for example.
function discussions(guild, channel) {
guildid = guild;
channelid = channel;
discussionsFunc();
async function discussionsFunc() {
try {
updateChannelID(guildid, channelid);
await getRecord({
guild_id: `${guildid}`
}, getFetchData);
const res1 = await fetch(url + `courses/${course}/discussion_topics?scope=unlocked`, {
method: "GET",
headers: {
Authorization: `Bearer ${access_token}`,
"Content-Type": "application/json",
},
});
const apiData = await res1.json();
for (discussions of apiData) {
const string = ["**TOPIC: " + discussions.title + "**", discussions.message + "\n"];
const res2 = await fetch(
`https://discordapp.com/api/channels/${channelid}/messages`, {
method: "POST",
headers: {
"Authorization": `Bot ${config.TOKEN}`,
Accept: "application/json",
"Content-Type": "application/json",
},
"Connection": "close",
body: JSON.stringify({
content: string.join('\n').replace(/(<([^>]+)>)/gi, "")
}),
}
);
const apiResponse = await res2.json();
}
} catch (err) {
console.log(err);
}
}
clearData();
};
function announcements(guild, channel) {
guildid = guild;
channelid = channel;
announcementsFunc();
async function announcementsFunc() {
updateChannelID(guildid, channelid);
try {
await getRecord({
guild_id: `${guildid}`
}, getFetchData);
const res1 = await fetch(url + `/announcements?context_codes[]=${obj}&latest_only=true`, {
method: "GET",
headers: {
Authorization: `Bearer ${access_token}`,
"Content-Type": "application/json",
},
});
const apiData = await res1.json();
console.log(apiData);
for (announcements of apiData) {
const string = [`\`\`\`${announcements.title}\n`, `${announcements.message}\n\`\`\``];
const res2 = await fetch(
`https://discordapp.com/api/channels/${channelid}/messages`, {
method: "POST",
headers: {
"Authorization": `Bot ${config.TOKEN}`,
Accept: "application/json",
"Content-Type": "application/json",
},
"Connection": "close",
body: JSON.stringify({
content: string.join('\n').replace(/(<([^>]+)>)/gi, "")
}),
}
);
const apiResponse = await res2.json();
console.log(apiResponse);
}
} catch (err) {
console.log(err);
}
}
clearData();
}
function assignments(guild, channel) {
guildid = guild;
channelid = channel;
assignmentsFunc();
async function assignmentsFunc() {
updateChannelID(guildid, channelid);
try {
await getRecord({
guild_id: `${guildid}`
}, getFetchData);
const res1 = await fetch(url + `/courses/${course}/assignments?order_by=due_at`, {
method: "GET",
headers: {
Authorization: `Bearer ${access_token}`,
"Content-Type": "application/json",
},
});
const apiData = await res1.json();
console.log(apiData);
var size = apiData.length - 1;
for (assignments of apiData) {
const string = [`\`\`\`Name: ${assignments.name}`, `Description:\n ${assignments.description}`, `Due Date: ${assignments.due_at}\n\`\`\``];
const res2 = await fetch(
`https://discordapp.com/api/channels/${channelid}/messages`, {
method: "POST",
headers: {
"Authorization": `Bot ${config.TOKEN}`,
Accept: "application/json",
"Content-Type": "application/json",
},
"Connection": "close",
body: JSON.stringify({
content: string.join('\n').replace(/(<([^>]+)>)/gi, "")
}),
}
);
const apiResponse = await res2.json();
console.log(apiResponse);
}
} catch (err) {
console.log(err);
}
}
clearData();
}
function getFetchData(document) {
obj = 'course_' + document._courseid;
course = document._courseid;
course1 = "_" + course;
url = 'https://' + document.prefix + '.instructure.com/api/v1/';
access_token = document.access_token;
console.log('obj = ' + obj + '\ncourse = ' + course + '\nurl = ' + url + '\naccess_token = ' + access_token);
}
module.exports = {assignments, discussions, announcements}
Also another advice to rename your functions, functions are verbs, not nouns, e.g. instead of assignments name it getAssignments or whatever it is doing.
UPD:
And looks like you are using wrong modules, Node.js uses CommonJS modules, so you have use require to import other modules unless you are using TypeScript or Babel.
Change your index.js file to
const express = require('express');
const{ assignments , announcements , discussions}
= require("./Fetch/fetchCalls.js");
var app = express();
app.use(express.json());
const PORT = 8080;
app.listen(PORT);
var guild;
var channel;
app.all('/assignments',(request) => {assignments(guild = request.body.guild, channel = request.body.channel);});
app.all('/discussions',(request) => {discussions(guild = request.body.guild,channel = request.body.channel); });
app.all('/announcements', (request) => {announcements(guild = request.body.guild,channel = request.body.channel);});
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 });
Can you please help me convert the following request to axios request.
const request = require('request-promise');
const data = {name:'pte', age:30}
const options = {secret:'34444'}
const opp = {
method: 'POST',
uri: 'https://something',
headers: { 'content-type': 'application/json' },
options,
body: JSON.stringify(data),
};
return request(opp);
const axios = require('axios')
const url = 'https://something'
const data = { name : 'pte', age : 30 }
const options = {
headers : {
'content-type' : 'application/json'
}
}
axios.post(url, data, header)
I'm trying to use 2checkout REST API
https://knowledgecenter.2checkout.com/API-Integration/REST_5.0_Reference#/introduction/authentication/json-encoded-requests
Here's a snippet of how i try to request
const axios = require('axios')
const moment = require('moment')
const saltedMd5 = require('salted-md5');
let now = moment().format('YYYY-MM-DD HH:MM:SS')
let vendorCode = '250207358831'
let toHash = vendorCode.length + vendorCode + now.length + now
let salt = '~0CSl)!M#4rZ|zX5QR&s'
const hash = saltedMd5(toHash, salt)
axios.get('https://api.2checkout.com/rest/5.0/subscriptions/?Email=customer%40email.com&AvangateCustomerReference=1234567&ExternalCustomerReference=abcdefg&Page=1&Limit=10&PurchasedBefore=2015-12-29&PurchasedAfter=2015-01-15&ExpireBefore=2016-05-22&ExpireAfter=2015-07-23&Type=regular&Aggregate=false', {
headers: {
'X-Avangate-Authentication': `code="${vendorCode}" date="${now}" hash="${hash}"`,
'Content-Type': 'application/json',
'Accept': 'application/json'
}
}).then(res => {
console.log(res)
}).catch(err => {
console.log(err)
})
It returns status code 500. Does someone know how to retrieve subscriptions using the 2checkout API?
class TwoCheckoutService {
tco: {
domain:string;
apiUrl: string,
apiUser:string,
apiPass:string,
sellerId:string,
privateKey:string,
secretKey:string,
demo:boolean,
};
constructor(private userService: UserService) {
this.tco = {=
apiUrl: 'https://api.2checkout.com/rest/6.0',
apiUser: "=",
apiPass: "=",
sellerId: "=",
privateKey: "=",
secretKey: "=",
demo: true,
// sandbox: false
};
}
private async _getAuthHeaders(): Promise<{[key:string]: string}> {
var code = this.tco.sellerId;
var date = moment().utc().format('YYYY-MM-DD hh:mm:ss');
var stringToHash = code.toString().length + code + date.toString().length + date;
var hmac = crypto.createHmac('md5', this.tco.secretKey);
hmac.update(stringToHash, 'utf8');
var hash = hmac.digest('hex')
var authHeader = `code="${code}" date="${date}" hash="${hash}"`
return {
'X-Avangate-Authentication': authHeader,
'Content-Type': 'application/json',
'Accept': 'application/json'
};
}
async getProducts() {
var url = this.tco.apiUrl + '/products/';
var headers = await this._getAuthHeaders();
console.log(headers);
var res = await Axios.get(url, {
headers: headers,
params: {
'Limit': 10,
'Page': 1,
},
validateStatus: (status)=>true
});
if(res.status === 200) return res.data;
return {
error: true,
data: res.data,
url: url,
headers: headers
}
}
}
#This is an example in typescript nodejs
##requirements
crypto
axios
2checkout api credentials