Encountering the 'Error: Module not found' while trying to import routes in Express

I have an ExpressJS application set up with Typescript. I am currently facing an issue while trying to add routes. Upon starting the app, I continuously receive the error message 'Error: Cannot find module 'routes/api'.

Below is my server.ts file:

import express from "express";
import * as api from "routes/api";

const app = express(),
  port = 3000;
  // api = require("routes/api");

app.use("/", api.router);

app.listen(port);

And here is my updated routes/api.ts file:

import express from "express";
import { gql } from "@apollo/client";

const router = express.Router(),
  client = require("../apollo");

router.post("/graphql/:owner/:name", (req, res) => {
  client
    .query({
      query: gql`
        query($owner: String!, $name: String!) {
          repository(name: $name, owner: $owner) {
            latestRelease {
              name
              isLatest
              createdAt
              publishedAt
              updatedAt
              url
              tagName
              resourcePath
            }
          }
        }
      `
    })
    .then((result) =>
      console.log(`GraphQL response: ${JSON.stringify(result)}`)
    );
});

export default router;

I have setup my eslint config in package.json but so far, adding import/extensions: 0 to the rules section and including plugin:import/typescript under the extends section did not resolve the issue. Here's the updated eslint Config from my package.json:

"eslintConfig": {
   ...

In addition, I have tried different export methods for router such as module.exports = router, export default router, and

api = require("routes/api"
without any success. Despite the correct file path being used, I continue to face this error. As I am new to Express, any assistance or guidance on this matter would be highly appreciated.

Update:

Here is my folder structure:

-package.json
-node_modules
-server.ts
-apollo.ts
-routes
 -- api.ts

Answer №1

After taking @Priyanka's advice and adjusting how api.ts was imported, I found that it did indeed resolve the issue. However, even after making this change, I encountered the Unable to resolve path to module error when running npm run lint. To completely fix the problem, I had to modify the export syntax in api.ts to use export default router. Additionally, I needed to make updates to the eslint configuration section of my package.json file. The guidance provided in a comment on this related StackOverflow post proved to be very helpful.

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

Is there a way to bring in a feature module from a personalized Angular library?

Just like in this particular inquiry, I crafted a unique Angular library (using Angular CLI 7.2.0) which consists of various feature modules: MyLibraryModule FeatureModule1 SomeComponent1 FeatureModule2 SomeComponent2 My goal is to selectivel ...

Send a response directly from a controller method in Express without using req and res

One of my methods updates data in Mongo, but I am facing a challenge with handling the response as the request never completes. This method will be used multiple times and does not have access to "req" and "res". Any suggestions on how to tackle this issue ...

Encountering an unforeseen token while using Webpack and React

Just diving into TypeScript and starting to explore React, I decided to follow along with the React & Webpack tutorial. After some research, I managed to fix most of the outdated issues, except for one. Whenever I attempt to run Webpack for transpiling ...

Issues with extensions during the Angular 9 Ivy compilation process

Good day! After upgrading a v8 project to v9, I encountered some errors related to extensions in the compiler. These errors are not present in another project that I also recently upgraded. The extensions, which are basic for constructors and prototypes, ...

Restrictions on file sizes when using multer for file uploads

I am currently working on a file uploader that needs to support various file types, such as images and videos. My goal is to apply different maximum file sizes for images (10MB) and videos (100MB) using a single instance of Multer, a middleware designed fo ...

Instead of receiving my custom JSON error message, Express is showing the server's default HTML error page when returning errors

I have set up a REST api on an Express server, with a React app for the front-end. The design includes sending JSON to the front-end in case of errors, which can be used to display error messages such as modals on the client side. Below is an example from ...

Issues arise when Typescript fails to convert an image URL into a base64 encoded string

My current challenge involves converting an image to base 64 format using its URL. This is the method I am currently using: convertToBase64(img) { var canvas = document.createElement("canvas"); canvas.width = img.width; canvas.height = img.he ...

What is the best way to access a variable from outside a function in Node.js?

app.get('/:id', function(req , res){ var ID = req.params.id ; //converter... var dl = new Downloader(); var i = 0; var videoTitle; // Declare the variable outside of the function dl.getMP3({videoId:req.params.id},functio ...

Clearing Documents in Express or Socket.io Made Easy

Currently, I am utilizing Express and Socket.io together in my project, a common practice among developers. In order to achieve a similar result to what document.write() does in JavaScript, I am seeking guidance. Is there a technique that would allow me ...

running a scheduled task on designated days of the month

Can someone confirm if the date set for the CRON task is correct? Tech Stack: Next.js/express.js The task should run after 7 days, on the 8th, 15th, 22nd, and 29th of each month, excluding February for obvious reasons. Cron version: "^1.7.0" This is wha ...

After destructuring, useParams may sometimes return as undefined

I'm encountering an issue with undefined variables being returned even after destructuring when using useParams(). I've tried various solutions but none seem to work for me. const App = () => { return ( <div className="container"> ...

Learn how to implement a file uploading web service in Node.js combined with JWT authentication

Looking to implement a file uploading web service with jwt Authentication where users can easily upload their files to the /upload route. Cloudinary will be utilized in my server to securely store the files. Additionally, users will have the ability to r ...

You are unable to declare an accessor within an ambient context when encountering the error in @material-extended/mde

I've been utilizing the @material-extended/mde package to incorporate a popover with dynamic HTML content. However, I'm encountering an error: error TS1086: An accessor cannot be declared in an ambient context. After researching the issue, it s ...

undefined event typescript this reactjs

I have come across the following TypeScript-written component. The type definitions are from definitelytyped.org. I have bound the onWheel event to a function, but every time it is triggered, this becomes undefined. So, how can I access the referenced el ...

Tips on recognizing the origin of incoming requests in a Node.js interface

In the development of my application using Node.js, Express.js, and Mongoose, I'm wondering how to determine if a request hitting my REST API service is coming from my front-end application rather than an unknown source. What steps or methods should I ...

Is it possible to make a fetch request within a post request in Express without encountering the error "can't set headers after they are sent to the client"?

Encountered a problem while trying to fetch data from an external server at using my localhost back-end server. I received an error message, but oddly enough, when the firewall on the other server is disabled, the post request works sp ...

Typeorm retrieve values of fields depending on their datatype

I have a TypeORM entity called SuperResource @Entity() export class SuperResource extends BaseEntity { @PrimaryGeneratedColumn() id: number; @OneToOne(() => Resource, {cascade: true, eager: true}) @JoinColumn() resource: Resource @Column({ ...

Differences between ng build --prod and ng --build aot in Angular 7

Recently, I successfully built an Angular 7 application using the command ng build --prod. However, I am now facing a dilemma regarding ng build --aot versus ng build --prod. Our application is currently deployed on ..., and although it runs successfully ...

When the button is clicked, a fresh row will be added to the table and filled with data

In my table, I display the Article Number and Description of werbedata. After populating all the data in the table, I want to add a new article and description. When I click on 'add', that row should remain unchanged with blank fields added below ...

Tips for creating a vue-cli application that can be customized post-build:

I have a functioning vue-cli application that I can easily build. However, I now need to create a single deployable build that can be used on multiple servers. The challenge is that depending on the server, I will need to adjust some basic variables such a ...