Guide to resolving domain names in express.js

I've been working on an expressJS script that includes a mongoDB fetch. My objective is to create an API that displays my JSON-based test list on the /api/testlist route.

When I try to access the index page, everything seems to be working fine. However, I'm facing issues with the API route.

It's quite strange because I can reach 'IP + port/api/testlist', but if I use my domain address instead, I get a 404 error. Interestingly, the index page loads fine with the domain address.

Below is the script I'm using:

const { MongoClient } = require('mongodb');
const express = require("express");

const app = express();
const port = 3000;
const uri = 'mongodb://localhost:27017';

const client = new MongoClient(uri);

try {
  client.connect();
  console.log('Connected to MongoDB');
} catch (err) {
  console.error('Error connecting to MongoDB:', err);
}

app.get("/", (req, res) => {
  res.sendFile(__dirname + "/index.html");
});

app.get("/api/testlist", async (req, res) => {
  try {
    const collection = client.db('test').collection('test');
    const result = await collection.find({}).toArray();
    
    if (result.length > 0) {
      res.json({ result });
    } else {
      res.json({ message: 'items not found'});
    }

  } catch (err) {
    console.error("Error querying MongoDB:", err);
    res.status(500).send("Error querying the database");
  }
});

app.listen(port, () => {
  console.log(`Server listening on port ${port}`);
});

I've attempted to configure the nginx server config and the mongoDB config, but without success.

There seems to be something off in the script that I haven't been able to pinpoint yet. Perhaps there's something missing or overlooked.

Answer №1

After some troubleshooting, I managed to resolve the issue by simply creating a new empty file named testlist next to my server.js script. Without any specific formatting, just a blank slate. Additionally, I made the decision to remove the /api from the route in my server.js file, simplifying it to just /testlist. Surprisingly, this adjustment allowed me to successfully access the API route and retrieve the list via the domain. It may seem odd, but sometimes the solution isn't always straightforward.

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

Prevent user input when an alert window is open

Users keep pressing the enter key multiple times when an alert box pops up, causing them to accidentally dismiss the message by hitting 'ok'. Is there a simple way to prevent key presses on alert windows and only allow mouse input? ...

Loop through an object with only one array using JavaScript

I have a specific object structure that I am trying to iterate through in order to find a particular value within the array. For example, I want to check if the user name is equal to user2. While I was able to accomplish this with two separate objects (cre ...

What could be the reason my CSS and Javascript animation is not functioning properly?

Currently working on creating a dynamic animation menu using CSS and Javascript, but encountering some issues. The concept involves having a menu with initially hidden opacity (using CSS), which becomes visible when the hamburger menu is clicked, sliding i ...

Utilize JavaScript to submit the FORM and initiate the 'submit' Event

Hey there! Here's the code I've been working on: HTML : <html> <body> <form enctype="multipart/form-data" method="post" name="image"> <input onchange="test();" ...

Using jQuery, you can submit a form easily

In my work with Django, I am developing a quiz web application that requires a form submission after answering each question. The questions are displayed correctly, but I am facing an issue when trying to submit the form with the answers. The answers to t ...

Only one JSON file is handled at a time, no duplicates are made

We start by utilizing the powerful D3 JavaScript library for initializing data documents, followed by creating a custom JavaScript script to handle data processing. An excerpt from the customized JavaScript script appears as follows: drawLegend(); ...

Developing a personalized error message pop-up system in Electron

I am currently in the process of developing an application for file backup, which involves a lot of reading and writing to the filesystem. While most parts of the app are functioning well, I am facing some challenges with error handling. In the image belo ...

Employing ng-show and other related features within directive "A"

After browsing through similar inquiries, I am still unable to comprehend the solution. If I have a directive available at this link: http://pastebin.com/QtAzGv62 and now need to incorporate the functionality of "ng-show" (or any other standard angular di ...

When attempting to execute Protractor tests, an error occurs stating that the object #<Object> does not possess the 'getInstance' method

Whenever I try to run my Protractor tests from the command line, all of them fail because the protractor object does not have the necessary methods. The error message I receive is: TypeError: Object # has no method 'getInstance' Although this ...

What distinguishes the sequence of events when delivering a result versus providing a promise in the .then method?

I've been diving into the world of Promises and I have a question about an example I found on MDN Web Docs which I modified. The original code was a bit surprising, but after some thought, I believe I understood why it behaved that way. The specific ...

Using VueJS Computed Property along with Lodash Debounce

I have been encountering a slowdown while filtering through a large array of items based on user input. I decided to implement Lodash debounce to address this issue, but unfortunately, it doesn't seem to be having any effect. Below is the HTML search ...

Accessing Parent and Child Values in AngularJS Selections

I am seeking advice from experts on how to achieve the following desired results: Expected workflow chart: https://i.sstatic.net/9ZmmT.png Here is the default view: https://i.sstatic.net/H6xkZ.png Scenario 1: By clicking on the number "1", all items f ...

Show only specific items in an AngularJS application

As a newcomer to AngularJS and the Ionic framework, I'm currently working with the basic Starter Tabs Ionic template. I would like to implement a "Favourite/Bookmark" feature for certain items and display them on a separate tab. The structure of my b ...

Move the footer to the bottom of the page

Is there a way to position my footer at the bottom of the screen and make it extend to the full width in a responsive manner? Custom CSS for Footer: * { margin: 0; } html, body { height: 100%; } .page-wrap { min-height: 100%; margin-bottom: -142p ...

What is the limitation of including a string constant with "</script>" inside a <script> block?

I am genuinely curious about this: I thought that the following code would be valid within an HTML document: <script> var test = "<script>why? </script>"; </script> However, it turns out that this leads to an "unterminated str ...

Having trouble extracting the ID from the URL using parameters

Just diving into the world of Express JS and MongoDB, so I appreciate your patience with me. Currently following a web development tutorial by Colt Steele. Take a look at my code: app.get("/:id",async(req,res)=> { const id= req.params[&apo ...

Spontaneously generating models

Explaining this concept can be a bit complex. I am tasked with creating an object that contains properties from dynamic HTML code. To illustrate, let's use an example: Firstly, here is my data object: var myObject = {Field1: 'Value1', Fiel ...

Is it seriously impossible to create a TTL index on a field that is already indexed?

According to the 10Gen Docs, it states: "You cannot create a TTL index on a field that already has an index." However, in practice, this seems to work without any issues. What is the actual meaning behind this statement from the documentation? In the ...

Add the slide number and total count in between the navigation arrows of the owl carousel

In my Angular application, I am utilizing an ngx owl carousel with specific configurations set up as follows: const carouselOptions = { items: 1, dots: false, nav: true, navText: ['<div class='nav-btn prev-slide'></div>' ...

Every time I attempt to insert a background image into a div using jQuery, I am consistently faced with a 404 error message

When I hit enter in my search bar, a new div is created each time. However, I am struggling to assign a background image to the created div as I keep receiving a 404 error in the console. Below is the code snippet I'm working with: function appendToD ...