Nodejs encountered when using express static resources hosted (express.static ()) bug

As follows: test.html page mounted on the server,

const express= require('express') 
const fs= require('fs') 
let app = express();
// app.use(express.static('node_modules'))
app.use(express.static('node_modules'))
app.listen('4000',()=>{
    console.log("http://127.0.0.1:4000")
})
app.get('/',(req,res)=>{
    fs.readFile('./test.html','utf-8',(err,data)=>{
        console.log(data)
        res.end(data)
    })
})

test.html following page for the demo of a wangEditor, jq resources into local

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>wangEditor demo</title>
</head>
<body>
    <div id="editor">
        <p></p>
    </div>
    <button class="getsomething">获取</button>
    <!-- 注意, 只需要引用 JS,无需引用任何 CSS !!!-->
    <script src="https://cdn.bootcss.com/wangEditor/10.0.13/wangEditor.js"></script>
     <script src="./node_modules/jquery/dist/jquery.js"></script>
    <script type="text/javascript">
        var E = window.wangEditor
        var editor = new E('#editor')
        // 或者 var editor = new E( document.getElementById('editor') )
        editor.create()
        let getsomething = document.querySelector('.getsomething');
        getsomething.onclick= function(){
            $.get({
                url:'http://127.0.0.1:4040/setids'
            })
            console.log(editor.txt.html())
        }
    </script>
</body>
</html>

This time has been set static resource hosting, but will complain when you call http://127.0.0.1:4000, errors can not find jq resources, as follows

Problems introduced (line 14 in test.html) In this case the reason for the bug of jq

<script src="./node_modules/jquery/dist/jquery.js"></script>由于

Solution

A law

Since the static resources managed (app.use (express.static ( 'node_modules'))) so the call when the resource does not need to add in html ./node_modules, i.e. introduction to the following

<script src="./jquery/dist/jquery.js"></script>

Act II

Or to set a virtual path, use the following code in the static resource management

app.use('/node_modules',express.static('node_modules'))

ps: If you use a virtual path aaa is amended as follows
js file

app.use('/aaa',express.static('node_modules'))

html cited

<script src="./aaa/jquery/dist/jquery.js"></script>由于

Guess you like

Origin www.cnblogs.com/axu1997/p/12289657.html