App.get() not working with express.js

Hello. I’m trying to create an API that connects to my bot’s dashboard, but when I try to access the api page, it doesn’t work. I’ve created the dashboard with express.js, and all the other methods are firing. Here’s the one that doesn’t work:

app.get("/api/:action", async function(req, res) {
  let apicodes = await db.fetch(`apicodes`)
  console.log('1')
  let action = req.params.action
  if (apicodes) {
    console.log('2')
	if (apicodes.keys.includes(req.query.key)) {
	  if (apicodes.secrets.includes(req.query.secret)) {
	  if (action) {
		if (action === 'check') {
			let check = await db.fetch(`gban_${req.params.userid}`)
			if (check) {
				res.send(check)
			} else {
				res.send('Not Banned')
			}
		} else {
			if (action === 'ban') {
				let user = req.query.userid,
					reason = req.query.reason,
					evidence = req.query.evidence,
					moderator = req.query.moderator,
					requester = req.query.botid;
				let request = {type: 'ban', userID: user, reason: reason, evidence: evidence, moderator: moderator, botid: requester, status: 'Not checked'}
				await db.set(`banrequests_${requester}`)
			} else {
				if (action === 'unban') {
					let user = req.query.userid,
						reason = req.query.reason,
						moderator = req.query.moderator,
						requester = req.query.botid;
					let request = {type: 'unban', userID: user, reason: reason, moderator: moderator, botid: requester, status: 'Not checked'}
					await db.set(`banrequests_${requester}`)
				} else {
					if (action === 'editban') {
						if (req.query.reason) {
							let user = req.query.userid,
								reason = req.query.reason,
								moderator = req.query.moderator,
								requester = req.query.botid;
							let request = {type: 'editban', userID: user, reason: reason, moderator: moderator, botid: requester, status: 'Not checked'}
							await db.set(`banrequests_${requester}`)
						} else {
							if (req.query.evidence) {
								let user = req.query.userid,
									evidence = req.query.evidence,
									moderator = req.query.moderator,
									requester = req.query.botid;
								let request = {type: 'editban', userID: user, evidence: evidence, moderator: moderator, botid: requester, status: 'Not checked'}
								await db.set(`banrequests_${requester}`)
							}
						}
					} else {
						if (action === 'requests') {
							let requester = req.query.botid
							let requests = await db.fetch(`banrequests_${requester}`)
							if (requests) {
								res.send(requests)
								} else {
									res.send('No requests.')
							}
						} else {
							if (action === 'checkcon') {
								res.status(200).send('OK.')
							}
						}
					}
				}
			}
		}
	  } else {
      console.log('2')
      res.send('Invalid API call method.')}//.status(401)
	 } else res.send('Invalid API auth secret.')//.status(401)
	} else res.send('Invalid API auth key.')//.status(401)
 } else res.send('API code check broken')//.status(401)
  });

Can someone please help me?

Can you please show some logs?

Its a bit hard to read with so many nested if’s that really belong on the same level.

It seems that most of your action handlers don’t send any response to the incoming request in express. By “not working” do you mean it seems nothing happens on the client side?

@TheBigerGamer I saw it at first sight. I was hoping you would too. Use “ifelse” instead of “else”

Oh gosh, there’s too many if-else statements, @SuperWaltC can point out where it is?

I saw this in only saw this and didn’t see ifelse statements

I didn’t saw it. And still can’t see it. And it don’t even triggers. It doesn’t run the code. I was expecting to have 1 in the console because of that console.log('1'), but it doesn’t show that.

And there’s no log. The console doesn’t show any error. Only shows this: <hidden ip> - - [26/Feb/2020:11:17:49 +0000] "GET /favicon.ico HTTP/1.1" 304 - "https://myprojectdomain/api" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.130 Safari/537.36"

EDIT: I tried to add

app.get("/test", function (req, res) {
res.send("test")
})

And it doesn’t work

Did you add app.listen?

Change else to ifelse

    .listen(client.config.dashboard.port, function() {
      client.log(
        "log",
        `Dashboard running on port ${client.config.dashboard.port}`,
        "INFO"
      );
    })

And wdym by changing else to ifelse?

The port has to be the port assigned to your glitch project. Try process.env.PORT

Where ever it says else, change it to ifelse

The port has been configurated by another way. And I already have a website setted up. I just can’t add more pages, for some reason.

And @SuperWaltC you mean:

if (something) {} ifelse {}

? Because that doesn’t seem to work. But I think I’ll use the switch statement.
And my problem isn’t the organisation of the code, but that the event app.get("/api/:action", async function(req, res) {…}) isn’t firing.

EDIT: These can cause any problem with APIs?

app.engine("html", require("ejs").renderFile);
  app.set("view engine", "html");

It would be

if (...) {...} else if (...) {...}

Oh. OK. And what about the other question?

Yes. What port are you using?

  1. And all the other pages of the website work fine! But why the events I add don’t work?

Just make a separate address for each action.

An example of how to send a response … see the last line

if (action === 'ban') {
    let user = req.query.userid,
        reason = req.query.reason,
        evidence = req.query.evidence,
        moderator = req.query.moderator,
        requester = req.query.botid;
    let request = { type: 'ban', userID: user, reason: reason, evidence: evidence, moderator: moderator, botid: requester, status: 'Not checked' }
    await db.set(`banrequests_${requester}`)
    res.send('banned') // try adding this line
}

Have formatted the code for you, do not disgrace yourself

const getAPICodes = async () => await db.fetch(`apicodes`);
const getBannedStatus = async id => await db.fetch(`gban_${id}`);
const banRequest = async (req, type) => {
  const { userid: userId } = req.params;
  const { reason, evidence, moderator, botid: requester } = req.query;
  const request = {
    type: type || "ban",
    userID: userId,
    reason: reason,
    evidence: evidence,
    moderator: moderator,
    botid: requester,
    status: "Not checked"
  };
  return await db.set(`banrequests_${requester}`);
};

const actionHandler = async (req, res) => {
  const apiCodes = await getAPICodes();
  const { keys: apiCodesKeys, secrets: apiCodesSecrets } = apiCodes;
  const { action, userid: userId } = req.params;
  const { key, secret } = req.query;
  const passingState =
    apiCodesKeys.includes(key) && apiCodesSecrets.includes(secret);

  if (!action || !apiCodes || !passingState) return res.status(401).json({
    message: "Unauthorized",
    code: 401
  })

  switch (action) {
    case "check": {
      const check = getBannedStatus(userId);

      if (check) {
        res.send(check);
      } else {
        res.send("Not Banned");
      }
    }

    case "ban": {
      res.json(banRequest(req, "ban"));
    }

    case "unban": {
      res.json(banRequest(req, "unban"));
    }

    case "editban": {
      res.json(banRequest(req, "editban"));
    }

    case "requests": {
      res.json(await db.get(`banrequests_${req.paramd.botid}`));
    }

    case "checkon": {
      res.sendStatus(200);
    }
  }
};

app.get("/api/:action", async (req, res) => await actionHandler(req, res));
1 Like