zoukankan      html  css  js  c++  java
  • nodejs使用express中静态资源托管(express.static())时遇到的bug

    如下:将test.html的页面挂载在服务器上,

    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如下,页面为一个wangEditor的demo,jq资源在本地引入

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

    此时已经设置了静态资源托管,但是调用http://127.0.0.1:4000时会报错,错误为找不到jq资源,如下

    此时bug的原因为jq的引入问题(test.html中14行代码)

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

    解决方法

    法一

    由于设置了静态资源托管(app.use(express.static('node_modules')))因此在html中调用资源的时候不需要加上./node_modules,即如下引入即可

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

    法二

    或者为其设置一个虚拟路径,在静态资源管理时使用如下代码

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

    ps:若使用aaa为虚拟路径则修改如下
    js文件

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

    html中引用

    <script src="./aaa/jquery/dist/jquery.js"></script>由于
  • 相关阅读:
    网络最大流算法—最高标号预流推进HLPP
    网络最大流算法—EK算法
    PROPAGATION_REQUIRED
    js左侧三级菜单导航代码
    Ubuntu上用premake编译GDAL
    2013数据结构课程设计之便利店选址(暴力枚举和随机函数两种做法)
    JAVA环境配置
    [K/3Cloud] 如何从被调用的动态表单界面返回数据
    document.getElementsByClassName在ie8及其以下浏览器的兼容性问题
    Java学习笔记51:数组转ArrayList和ArrayList转数组技巧
  • 原文地址:https://www.cnblogs.com/axu1997/p/12289657.html
Copyright © 2011-2022 走看看