I want to validate the input that the endpoint receives upon invoking it. Therefore, I installed express-validator in my NodeJS web application. However, when I try to make use of it, it throws the error:
Cannot find module 'express-validator' or its corresponding type declarations
This happens, when I import it (i.e., import { validationResult } from "express-validator";
) or set it as an constant and require it. In the latter, it states that it cannot find the module. I have dockerized the project and this is the the dockerfile I have set up:
FROM node:12
WORKDIR /app
COPY package*.json ./
RUN npm install
COPY . .
EXPOSE 8000
CMD ["npm", "run", "dev"]
Currently, I am not running a production version, which is why I am running with dev. This is my docker-compose file:
services:
db:
image: postgres:12
environment:
- POSTGRES_DB=server_side
- POSTGRES_USER=postgres
- POSTGRES_PASSWORD=123321
app:
build:
context: .
dockerfile: Dockerfile
volumes:
- ./src:/app/src
ports:
- "8000:8000"
depends_on:
- db
environment:
- POSTGRES_DB=server_side
- POSTGRES_USER=postgres
- POSTGRES_PASSWORD=123321
- POSTGRES_HOST=db
When installing the module, it gets added to my dependencies:
{
"name": "Servier-side",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"build": "tsc",
"dev": "concurrently \"nodemon\" \"nodemon -x tsoa spec\"",
"start": "node build/index.js",
"predev": "npm run swagger",
"prebuild": "npm run swagger",
"swagger": "tsoa spec",
"typeorm": "node --require ts-node/register ./node_modules/typeorm/cli.js",
"migrate:generate": "npm run typeorm migration:generate -- -n",
"migrate:run": "npm run typeorm migration:run",
"migrate:revert": "npm run typeorm migration:revert",
"schema:drop": "npm run typeorm schema:drop"
},
"keywords": [],
"author": "",
"license": "ISC",
"devDependencies": {
"@types/express": "^4.17.13",
"@types/morgan": "^1.9.3",
"@types/node": "^16.11.10",
"@types/swagger-ui-express": "^4.1.3",
"concurrently": "^6.4.0",
"nodemon": "^2.0.15",
"ts-node": "^10.4.0",
"typescript": "^4.5.2"
},
"dependencies": {
"express": "^4.17.1",
"express-validator": "^6.13.0",
"morgan": "^1.10.0",
"pg": "^8.7.1",
"reflect-metadata": "^0.1.13",
"swagger-ui-express": "^4.1.6",
"tsoa": "^3.2.1",
"typeorm": "^0.2.41"
},
"nodemonConfig": {
"watch": [
"src"
],
"ext": "ts",
"exec": "ts-node src/index.ts"
}
}
I would really appreciate if someone could shed light on the matter. Just for the sake of excluding possible reasons, I also tried with Joi, but I ended up with the same issue. So, what I would like to understand is what is causing the issue - Why does is work for the rest of the dependencies and not this one and what should be done to resolve the issue?
CodePudding user response:
This kind of error is usually when you need to add the @types dependency for the module.
CodePudding user response:
Running docker compose with the build flag docker-compose up --build
fixed the issue.