我已经启动了带有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.
你们知道这是怎么回事吗?
答案 0 :(得分:3)
您为公共/静态文件映射了错误的根目录:
app.use(exp.static('public'));
应该是:
app.use(exp.static('www'));