当我在html中链接javascript文件时,它将请求发送到服务器并导致错误

时间:2018-09-30 07:03:51

标签: javascript html node.js express ejs

我在后端使用express和node.js,在前端使用ejs模板引擎。我的app.js看起来像这样

app.get('/book/:id', (req, res)=>{
var book_id = req.params.id;
console.log('this book :', book_id);
Book.findOne({
    book_id
}).then((book)=>{
    res.render('book.ejs', {book, title: "Book"});
}).catch((e)=>{
    // console.log(e);
});
});

book.ejs文件

<!DOCTYPE html>
<html>
<head>
    <title><%= title %></title>
    <script type="text/javascript" src="jquery-3.3.1.min.js"></script>
    <script type="text/javascript" src="books.js"></script>
</head>
<body style="font-family: arial">
    <h1><%= title %></h1>
</body>
</html>

但是当我将页面路由到book / 1234时,我在服务器中获得了以下登录信息

this book : 1234
this book : jquery-3.3.1.min.js
this book : book.js

为什么将jquery-3.3.1.min.js和book.js发送到book /:id路由?我只发送book / 1234,但jquery-3.3.1.min.js和book.js也发送到服务器并导致错误。

浏览器控制台日志是这个

GET http://localhost:3000/book/jquery-3.3.1.min.js net::ERR_ABORTED 500 (Internal Server Error)
1234:1 Refused to execute script from 'http://localhost:3000/book/jquery-3.3.1.min.js' because its MIME type ('text/html') is not executable, and strict MIME type checking is enabled.
1234:6 GET http://localhost:3000/book/books.js net::ERR_ABORTED 500 (Internal Server Error)
1234:1 Refused to execute script from 'http://localhost:3000/book/books.js' because its MIME type ('text/html') is not executable, and strict MIME type checking is enabled.

3 个答案:

答案 0 :(得分:1)

由于脚本链接具有相对路径,所以它们是从当前路径/book加载的。

它们应该具有绝对路径:

<script type="text/javascript" src="/jquery-3.3.1.min.js"></script>
<script type="text/javascript" src="/books.js"></script>

或应指定基本URL:

<base href="/">

答案 1 :(得分:0)

我认为您的book.ejs文件位于'/ book'的路由下。如果是这样,您的脚本标签(如<script type="text/javascript" src="books.js"></script>)将访问/book/book.js的路由,而不是您的资产。 因此,您应该像这样/book.js那样设置src属性,并确保可以访问资产。

答案 2 :(得分:0)

您正在src属性中使用相对路径。由于您是从/books/<id>提供页面,因此,如果您使用相对路径,浏览器会将其理解为/books/(relative_path_of_resource),因此当遇到这些链接时,它将向books / jquery.js发送请求,并且books / books.js

您应该将链接转换为指向js文件的正确静态路径。请参阅此链接-https://expressjs.com/en/starter/static-files.html,以了解如何投放静态文件,设置投放后,您可以将链接更改为/static/books.js/static/jquery.js