【问题标题】:localhost:3000/app.js instead of app/www/app.jslocalhost:3000/app.js 而不是 app/www/app.js
【发布时间】:2018-08-22 15:15:39
【问题描述】:

我已经使用 Express 启动了一个服务器,并将 MongoDB 附加到它上面。我把链接放到 HTML 网页中使用的app.js 文件,但是我知道为什么,但是服务器想从 localhost:3000 加载 js 文件,而不是从我的文件夹中加载。这是我的项目文件夹:

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

app.js 文件为空,但 index.html 不是

<!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>

最后是服务器脚本 (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");
    });
})

然后我用nodemon index 启动了我的服务器并加载了它,但出现了两个错误:

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.

你们知道怎么回事吗?

【问题讨论】:

    标签: javascript html node.js mongodb get


    【解决方案1】:

    您为公共/静态文件映射了错误的根目录:

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

    应该是:

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

    【讨论】:

      猜你喜欢
      • 2019-10-11
      • 1970-01-01
      • 2019-05-17
      • 2020-04-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-08-11
      相关资源
      最近更新 更多