Search code examples
javascripthtmlnode.jsmongodbget

localhost:3000/app.js instead of app/www/app.js


I've launched a server with Express and attached MongoDB to it. And I put link to app.js file that is used in HTML webpage, but Idk why, but server wants to load js file from localhost:3000, but not from my folder. Here's my project folder:

app
|_node_modules
|_www
  |_app.js
  |_index.html
|_index.js
|_user.js
|_package.json
|_package-lock.json

app.js file is empty, but index.html isn't

<!DOCTYPE html>
<html lang="en" dir="ltr">
  <head>
<script src="https://code.jquery.com/jquery-3.3.1.min.js" charset="utf-8"></script>
<script src="app.js" charset="utf-8"></script>
    <meta charset="utf-8">
    <style>
input {font-size: 30px}
    </style>
    <title></title>
  </head>
  <body>
<button onclick=hashGen()>GENERATE HASH</button>
  <form action="/post" method="post">
<input type=text name=pass id=hash>
<input type=number name=pin>
<input type=submit value=submit />
  </form>
  </body>
</html>

And finally server script (index.js):

// Import modules
exp = require('express');
path = require('path');
parser = require('body-parser');
db = require('mongoose');
User = require('./user.js').User;
app = exp();

// Express & Mongoose params
app.listen(3000);
app.use(exp.static('public'));
app.use(parser.urlencoded({ extended: false }));
app.use(parser.json());
db.Promise = global.Promise;
db.connect("mongodb://localhost:27017/node-demo",{ useNewUrlParser: true });

// Load page
app.get('/',(req,res)=>{
  res.sendFile(path.join(__dirname + '/www/main.html'));
})

// Take input & send to db
app.post('/post',(req,res)=>{
  let data = new User(req.body);
  data.save().then(item =>{
    res.send(req.body.user + ' added.')
  }).catch(err => {
      res.status(400).send("unable to save to database");
    });
})

Then I launched my server with nodemon index and it loaded, but with two errors:

GET http://localhost:3000/app.js 404 (Not Found)
localhost/:1 Refused to execute script from 'http://localhost:3000/app.js' because its MIME type ('text/html') is not executable, and strict MIME type checking is enabled.

Do u guys know what's wrong?


Solution

  • You mapped wrong root directory for your public/static files:

    app.use(exp.static('public'));
    

    Should be:

    app.use(exp.static('www'));