ReferenceError: require is not defined (on my rest api)

Viewed 508

doesn't work Hey guys i have tried so many ways to fix this problem but i can´t really find a answer fot this.

I am making an rest API for my web site in react, and i am very new to this... i am trying to connect my server.js file to my routes.js file but it doesn´t let me beacuse it doesn´t recognise de "require".

    import express from "express";
import cors from 'cors';
import mysql from 'mysql';
const routes = require('./routes');

app.use(cors());
const app = express();

const connection = mysql.createConnection({
    host: 'localhost',
    user: 'root',
    password: '',
    database: 'marioquiz'
});


app.use(express.json());
app.use(routes);
app.use('/User',routes);


app.get('/',(req,res)=>  res.send('O servidor esta a funcionar...'));

app.listen(5000);

And returns me this Error:

file:///C:/Users/Mario/Desktop/Master/Backend/src/server.js:4

const routes = require('./routes');
           ^

ReferenceError: require is not defined
    at file:///C:/Users/Mario/Desktop/Master/Backend/src/server.js:4:16
    at ModuleJob.run (internal/modules/esm/module_job.js:146:23)
    at async Loader.import (internal/modules/esm/loader.js:165:24)
    at async Object.loadESM (internal/process/esm_loader.js:68:5)
1 Answers

The require keyword is used for CommonJS modules, but it looks like you've configured Node.js to run your application using ECMAScript modules. The equivalent way to bring in routes using ECMAScript modules is something like:

import { routes } from './routes.js';

Bear in mind that you will have to write your routes.js file to be ECMAScript modules compatible also, something like:

const routes = [
  ...
];

export { routes }; 
Related