如何使用Express Server在HTML中加载JS文件 [英] How to load JS file in html using express server

查看:303
本文介绍了如何使用Express Server在HTML中加载JS文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已将js放在公共目录中,并尝试将js加载到HTML中,但出现错误.

I have put my js in a public directory and trying to load the js in my HTML but getting an error.

var express=require('express');
var bodyparser=require('body-parser');
var path=require("path");
var multer=require("multer");
console.log(__dirname);
var app=express();
var upload = multer({ dest: __dirname + '/uploads/' });
// app.set('views', __dirname + '/views');
app.use(bodyparser.json());
app.use(bodyparser.urlencoded({extended:true}));
app.use(express.static(path.join(__dirname, 'public')));
 app.engine('html', require('ejs').renderFile);
app.get('/',(req,res)=>{
     res.render('some.ejs');
});
app.post('/',upload.single('upl'),(req,res)=>{
    console.log(req.body);
    console.log(req.file);
})
app.listen(3000,()=>{
    console.log("server is up");
})


这是我的HTML代码,用于加载JS:


Here is my HTML code to load the JS:

<script src="/public/web.js"></script>

目录结构

├ public
| └ web.js
├ views
| └ some.ejs
└ server.js

推荐答案

要将文件从服务器提供给客户端,必须将目录声明为静态目录.

To serve a file from the server to the client, you must declare the directory as a static.

使用快递,您可以使用

app.use(express.static('PublicDirectoryPath'))

要获取公共目录下的文件,

To fetch the files under the public directory,

<script src="FilePathUnderPublicDirectory"></script>

更新的代码:

现在您的server.js文件应该是

var express=require('express');
var bodyparser=require('body-parser');
var path=require("path");
var multer=require("multer");
console.log(__dirname);
var app=express();
app.use(express.static('public'));
var upload = multer({ dest: __dirname + '/uploads/' });
// app.set('views', __dirname + '/views');
app.use(bodyparser.json());
app.use(bodyparser.urlencoded({extended:true}));
app.use(express.static(path.join(__dirname, 'public')));
 app.engine('html', require('ejs').renderFile);
app.get('/',(req,res)=>{
     res.render('some.ejs');
});
app.post('/',upload.single('upl'),(req,res)=>{
    console.log(req.body);
    console.log(req.file);
})
app.listen(3000,()=>{
    console.log("server is up");
})

请注意,我在以下位置将公用目录声明为静态目录: 第7行.

Notice that I declare the public directory as a static directory at line 7.

由于您的web3.js直接位于public目录下,因此在您的前端,请使用

Since your web3.js is directly under the public directory, in your front end, use

<script src="/web.js"></script>

有关更多信息,请查看文档.

For more, please check the doc.

这篇关于如何使用Express Server在HTML中加载JS文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆