如何在Express/Node.js提供的index.html中正确包含外部CSS和JS文件? [英] How to properly include external css and js files in index.html served with express/nodejs?

查看:94
本文介绍了如何在Express/Node.js提供的index.html中正确包含外部CSS和JS文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将我的html包装在nodejs express应用程序(express的最新版本)中.我尝试使用res.sendFile发送"index.html"文件.我遇到一个问题,在浏览器中加载页面时有很多404,因为它找不到我的任何js或css文件.我的js文件位于bower_components目录中,有些位于"js"目录中.我的CSS文件位于"css"目录中.

I am trying to wrap my html in a nodejs express app (latest version of express). I try using res.sendFile to send my "index.html" file. I am running into an issue where there are a lot of 404s when loading the page in a browser because it can't find any of my js or css files. My js files are in the bower_components directory, some are in "js" directory. My css files are in a "css" directory.

其中一个的路径是:

/bower_components/jquery/dist/jquery.min.js

在我的server.js文件和index.html文件中进行更新以使其能够找到所有"css"和"js"文件的最佳方法是什么?

What is the best way to update in my server.js file and my index.html file so that it can find all the "css" and "js" files?

推荐答案

您可以使用指令 express .static

var server = express();
server.use(express.static(path.join(__dirname, 'static')));

它将寻找一个静态文件夹来提供您的静态文件.只需将css和js文件放在此文件夹中,然后在模板的<head>部分(以您的情况为index.html)中引用它们

It will look for a static folder to serve your static files. Just put your css and js files in this folder and reference them in the <head> part of your templates (index.html in your case)

这篇关于如何在Express/Node.js提供的index.html中正确包含外部CSS和JS文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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