简体   繁体   English

如何使用node.js在html上加载javascript文件

[英]How to load a javascript file on the browser with a html using node.js

I'm working on a project and want to run some javascript code on client side, how can i load a javascript file for it to run on the browser and not on the server? 我正在研究一个项目,并希望在客户端运行一些javascript代码,如何加载一个javascript文件,使其在浏览器上运行而不是在服务器上运行?

I've tried using sendFile(), reference the file in the html and various advice I've found online, none seem to work 我已经尝试过使用sendFile(),引用html中的文件以及我在网上找到的各种建议,似乎都没有工作

I want the browser to show me in sources the html file and the javascript file that i'm referencing in the html and in the sendFile() 我希望浏览器在源代码中向我显示html文件和我在html和sendFile()中引用的javascript文件

everytime that i try to load it i get this message from the console Error: ENOENT: no such file or directory, stat 'C:\\Proyectos\\Walletpublic' 每次我尝试加载它我从控制台收到此消息错误:ENOENT:没有这样的文件或目录,stat'C:\\ Proyectos \\ Walletpublic'

Javascript code: Javascript代码:

var app = express();
app.use(express.static('./public/confirm.js'));
app.get('/ide', (req, res) => {
    res.render('identification.ejs')
    res.sendFile(path.join(__dirname + 'public'))
    console.log(req.url)
})```

Html code:

```<body>

        <p>Complete the folowing input bars acordinly</p>
        <input id="name" type="text" name="name" placeholder="First and last name"/>
        <input id="id" type="number" name="id" placeholder="Id number"/>
        <input id="homeAd" type="text" name="homeAd" placeholder="Home address"/>
        <input id="posCod" type="number" name="posCod" placeholder="Postal Code"/>
        <input id="phone" type="number" name="phone" placeholder="Phone"/>
        <input id="homePhone" type="number" name="homePhone" placeholder="Home phone number"/>
        <input id="email" type="text" name="email" placeholder="Email"/>
        <br>
        <button id="ideconfi">Sumbit</button>
    </script src="../public/confirm.js">```



express.static needs to be passed "the root directory from which to serve static assets" express docs . express.static需要传递“从中提供静态资产的根目录” 表达文档 The top line app.use(express.static('./public/confirm.js')); 顶线app.use(express.static('./public/confirm.js')); should be: 应该:

  • app.use(express.static(path.join(__dirname, 'public')));
 // express on its own has no notion // of a "file". The express.static() // middleware checks for a file matching // the `req.path` within the directory // that you pass it. In this case "GET /js/app.js" // will look for "./public/js/app.js". 

app.use(express.static(path.join(__dirname, 'public'))); app.use(express.static(path.join(__ dirname,'public')));

— another example ( from the Express static-files example on GitHub ) - 另一个例子( 来自GitHub上的Express静态文件示例

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM