Uncaught ReferenceError: require is not defined---"can't use import outside module"

Viewed 45

// server.js file // 

const express = require('express');
const cors = require('cors');
const bodyParser = require('body-parser');
const mysql = require('mysql');

// Start up an instance of app
const app = express();

/* Middleware*/
//Here we are configuring express to use body-parser as middle-ware.
app.use(bodyParser.urlencoded({
  extended: false
}));
app.use(bodyParser.json());

// Cors for cross origin allowance
app.use(cors());

// Initialize the main project folder
app.use(express.static('website'));


// Setup Server
const port = 8800;
// callback function to validate the server is running
app.listen(port, function() {

  console.log('Server running successfully');
  console.log(`Server running on port ${port}`);
})
const db = mysql.createConnection({

  host: "localhost",
  user: "root",
  password: "",
  database: "nodemysql",

});
//exports.db = db;

//Connect to MySQL

db.connect((err) => {

  if (err) {

    throw err;

  }

  console.log("MySql Connected");

});

function editing() {

  let id = "5";

  let newName = "Modified Name";

  let sql = `UPDATE employee SET name = '${newName}' WHERE id = ${id}`;

  let query = db.query(sql, (err) => {

    if (err) {

      throw err;
    }
  });
  console.log(newName)
};

module.exports = {
  editing
};


// app.js file // 
import {editing} from '../server';
save.addEventListener("click", editing)
<!DOCTYPE html>
<html>

<body>

  <script src="app.js" type="text/javascript"></script>
  <script src="../server.js" type="module"></script>
  <button id="save">Click me</button>
</body>


</html>

I am developing a simple web calculation page using html file (index.html) and 2 JavaScript files one is server.js and the other is app.js. I want to import "editing" function from the server file to use in app file, but I always get the error "Uncaught ReferenceError: require is not defined " or "can't use import outside module". I added the "type: module" in package.json file but it didn't work also. I tried to reference the two JavaScript files in the html file and giving "module" type to the server.js file but it gives another error in the browser. I tried to change the extension of both JavaScript files to .mjs but didn't solve the problem. I simply want to trigger the "editing" function from the server.js file upon clicking the "Click me" button. I have attached a code snippet

Need help please

0 Answers
Related