Last modified: Jun 24, 2025 By Alexander Williams
Fix Error: Cannot find module 'cors'
If you see the error Cannot find module 'cors', don't worry. This is a common issue in Node.js. It means the 'cors' package is missing. Let's fix it.
What causes the 'Cannot find module cors' error?
This error occurs when Node.js cannot locate the cors
module. The main reasons are:
1. The package isn't installed.
2. The module isn't in your node_modules folder.
3. The installation was corrupted.
How to fix the error
Follow these steps to resolve the issue:
1. Install the cors package
First, install the cors
package using npm. Open your terminal and run:
npm install cors
If you use Yarn, run:
yarn add cors
2. Check your package.json
After installation, verify that cors
appears in your dependencies:
"dependencies": {
"cors": "^2.8.5"
}
3. Reinstall node_modules
If the error persists, delete node_modules and reinstall:
rm -rf node_modules
npm install
4. Check your import statement
Ensure you're requiring cors
correctly in your code:
const cors = require('cors'); // Correct way
Common mistakes to avoid
1. Installing globally instead of locally.
2. Misspelling the package name.
3. Not saving the package to package.json.
Example: Using cors in Express
Here's a complete example of using cors
in an Express app:
const express = require('express');
const cors = require('cors'); // Import cors
const app = express();
app.use(cors()); // Enable CORS for all routes
app.get('/', (req, res) => {
res.send('Hello World!');
});
app.listen(3000, () => {
console.log('Server running on port 3000');
});
Similar errors like Cannot find module 'express' or Cannot find module 'body-parser' can be fixed the same way.
Troubleshooting tips
If the error continues:
1. Check your Node.js and npm versions.
2. Try clearing npm cache with npm cache clean --force
.
3. Verify your project's directory structure.
Conclusion
The Cannot find module 'cors' error is easy to fix. Just install the package correctly. Always check your dependencies. For other module errors like Node.js module issues, the solution is similar.