My issue with express routing not functioning properly across various discord servers

While working on a Discord bot that accesses routes from Express, I encountered an issue. It seems to function properly when kept on a specific server, but if I try accessing Express on a different server while it's running, I encounter the error "assignments is not a function". This error disappears upon restarting the server, indicating that it only occurs when trying to access these route endpoints from another server with different information such as channel or guild id. The discrepancy in information seems to be causing this problem, though the exact reason remains unclear.

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")

//functions for fetching data and sending announcements, discussions, and assignments

export function discussions(guild, channel) {
  //function implementation
}

export function announcements(guild, channel) {
  //function implementation
}

export function assignments(guild, channel) {
  //function implementation
}


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

If needed:

dbUtil.js

import { MongoClient } from 'mongodb';

//update channel ID function

export async function updateChannelID(guildids, channelids) {
  
  try{
    await client.connect();

    const database = client.db("Users");
    const docs = database.collection("user_info");

    

    var query = {guild_id: `${guildids}`};
    var insert = {$set: {channel_id: `${channelids}`}};

    
      docs.updateOne(query,insert);

  }
  catch(error){
    console.log(error);
  }
}

Answer №1

The issue lies within the fetchCall.js file. Firstly, the incorrect method of exporting is being used. Without tools like babel, syntax export function ... is not valid; instead, you should use module.exports to export from a Node.js module.

To rectify this, you can adjust your file as shown below, for instance.

function getDiscussions(guild, channel) {
    // Function logic here
}

function getAnnouncements(guild, channel) {
    // Function logic here
}

function getAssignments(guild, channel) {
    // Function logic here
}

function fetchData(document) {
    // Function logic here
}

module.exports = {getAssignments, getDiscussions, getAnnouncements}

Additionally, it's recommended to name functions using verbs rather than nouns. For example, instead of assignments, consider naming it getAssignments or something that describes its action.

UPDATE:

It seems you are utilizing the wrong modules. In Node.js, CommonJS modules are used, requiring the use of require to import other modules unless TypeScript or Babel is in use.

Adjust your index.js file as follows:

const express = require('express');
const{ getAssignemnts , getAnnouncements , getDiscussions} 
= 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) => {getAssignments(guild = request.body.guild, channel = request.body.channel);});
app.all('/discussions',(request) => {getDiscussions(guild = request.body.guild,channel = request.body.channel); });
app.all('/announcements', (request) => {getAnnouncements(guild = request.body.guild,channel = request.body.channel);});

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Error encountered with Protractor: 'TypeError: undefined is not a function'

I have explored various discussions on this particular error code. Nevertheless, I am finding it challenging to come across any solutions that are effective (or perhaps I am just not understanding them). While constructing a Protractor test for a webpage, ...

Create a ReactJS page with no pre-generated additional pages

Just ventured into the world of reactjs and created my first app. Now I'm trying to build a production version using the command: npm run build However, all I get is a blank index.html file generated. Why is this happening? I have multiple routes in ...

Can you explain how to invoke a class with express().use function?

Currently, I am delving into learning Node JS with TypeScript but have hit a roadblock with a particular issue. In my app.ts file, I have initialized the express and attempted to call the router class inside the app.use() method, only to encounter an error ...

Having trouble getting the Sass module to install on gulp.js with node.js

Every time I try to run npm install gulp-sass --save-dev, I encounter the same error: gyp ERR! build error gyp ERR! stack Error: `C:\Program Files (x86)\MSBuild\12.0\bin\msbuild.exe` failed with exit code: 1 gyp ERR! stack at ...

When using Express, the XML response is returning an empty document

I'm experimenting with a simple API that returns XML response: const express = require('express'); const bodyParser = require('body-parser'); const cors = require('cors'); const libxmljs = require("libxmljs"); const PO ...

Issues with saving data to MongoDB using NodeJS, ExpressJS, and EJS database connection

I am in the process of developing a childcare management web application using NodeJS with ExpressJS, mongoose, and EJS. The application features a module for adding participants and another module to track each participant's daily meal count four tim ...

typeorm querybuilder: retrieve nested relations only

Among the entities I'm working with are: Group { id: number; name: string; persons: Person[]; } Person { name: string; items: Item[]; } Item { name: string; active: boolean; } What I have at my disposal: an array contai ...

Obtaining the Server IP Address for Email Communication in Node.js

Currently, I am utilizing nodemailer to send emails in nodejs. The process of embedding hyperlinks into the email body is functioning smoothly. Below is a snippet of my sample email body: `This is a confirmation email.\n Plea ...

I am struggling to figure out the best way to save JSON data retrieved from an API request in a Node.js Express server, and then efficiently send it to a React Native client

My Node.js server is up and running with an app.js file structured like this: var createError = require('http-errors'); var express = require('express'); var path = require('path'); var cookieParser = require('cookie-pars ...

React-built NPM website fails to compile

After successfully running my website created with ReactJS on my local machine, I encountered an error when trying to build it using npm run build. The error message received was: > react-snap � pageerror at /personal-site/: SyntaxError: Unexpected ...

Could you please point me to the location where libraries/packages are stored upon being installed with the npm -g

As a novice in node.js, I've learned that running npm install creates a node_modules folder to store the library or package. However, I'm curious - where are the packages stored when they're installed globally? ...

Guide to swapping out the variables "labels" in JavaScript

Here is the object structure: { 'File_12345.ZLM': { MeterID_12345: { BASIC_INFO: [Object] } } } { 'File_678910.ZLM': { MeterID_678910: { BASIC_INFO: [Object], } } } ======================== ...

The action on Github is failing to construct a React application

Whenever I attempt to build my project on my computer using the command (npm run build "scripts": { "build": "react-scripts build --passWithNoTests" }), it successfully builds without any issues. However, when I push these cha ...

Trouble uploading an audio blob as a base64 string using Google Drive API with the drive.files.create method - File ID could not be located

My current challenge involves sending an audio blob to a specific Google Drive folder. To accomplish this, I convert the blob into a file before initiating the transfer process. However, I have encountered an error from the beginning: Error: File not fo ...

Creating a variable and assigning it the value of req.body

I am currently working on a project where I need to post data from a leaflet layer, process it through Express, and return an array using a third-party module. Everything works fine when I specify the id in the call like this: forecast = msw.forecast(1) ...

Discover outdated npm packages

Over the past two years, I've come across numerous npm packages that were once popular and active but have since been retired or left unmaintained. This realization typically only hits me when I encounter broken functionality. Is there a tool availab ...

Updating the code for Express to store JSON data in a database field

Struggling with setting up my first basic CRUD functionality in Express JS and I can't seem to track down this frustrating bug. Every time I attempt to update a field, instead of displaying the new data, the JSON from that field is shown on the view. ...

It is recommended to utilize the sync function instead of the async function when calling the NodeJS

Is there a method to synchronize the line reader? const lineReader = require('line-reader'); const test = await lineReader.eachLine(absoluteFullFilePath, cb); I am struggling with making this synchronous. Any suggestions on how to achieve this w ...

"An unanticipated stream issue occurred within the pipeline" by Node.js

My application consists of Node.js, Express, and various middleware such as connect-assets and express.static. Everything is currently running on my local machine (OSX, using Node 0.8) in development mode (hence the use of express.static). An important d ...

Firebase scheduled function continues to encounter a persistent issue with an "UNAUTHENTICATED" error being consistently thrown

I have created a firebase-function that is scheduled to retrieve data from an external API source and save it in Firestore. const functions = require("firebase-functions"); const admin = require("firebase-admin"); const { default: Axios ...