使用express.js与脚本,css和图像一起提供html文件 [英] Using express.js to serve html file along with scripts, css, and images

查看:78
本文介绍了使用express.js与脚本,css和图像一起提供html文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试构建我的第一个Web应用程序,我从前端开始使用jquery和jquery mobile以及许多我已经拥有大量前端的插件,并且所有这些插件都源于单个html文件(因为jquery mobile在同一个文件中使用页面div),但该应用还有一个主要的js文件,一个css文件以及插件等中包含的许多css和js文件.我现在正尝试使用node.js和express.js添加数据库和其他后端功能,但是当我使用res.sendFile()来提供html脚本和CSS的功能时,我遇到了麻烦加载后,当我尝试提供目录时,目录中的所有内容都显示为链接,我当然不希望在公共视图中显示该链接(尽管当我执行此操作并单击html文件链接时,它仍然可以正常工作.

I'm trying to build my first webapp, I started with the frontend and using jquery and jquery mobile as well as many plugins I have a significant frontend already, and all of it stems from a single html file (since jquery mobile uses page divs within the same file) but there is also a main js file for the app, a css file and many css and js files included from plugins and the like. I'm now trying to add in database and other backend functionality using node.js and express.js, but I've run into a wall, when I use res.sendFile() to serve up the html the scripts and css don't load, and when I try to serve the directory everything is in it shows the directory as links which I certainly don't want in the public view (though when I do this and click the html file link it works fine.

我想知道的是如何使用express来实现a)提供一个外部设计和维护的前端,以及b)允许该前端将请求发送回服务器(这样我就可以使用表格并获取数据和东西) ?

What I want to know is how do I use express to a) serve up an externally designed and maintained frontend and b) allow that frontend to send requests back to the server (so I can use forms and get data and stuff)?

推荐答案

您应该执行以下操作:

  1. 提供您的静态文件
  2. 创建一个API服务器,以侦听来自前端应用程序的请求

1.服务您的静态文件

要通过Express提供静态文件,请阅读链接.

您基本上将其添加到您的快速应用中:

You'll basically add it to your express app:

app.use( express.static( __dirname + '/client' ));

'/client'是包含您的前端应用程序文件的文件夹的名称.

Where '/client' will be the name of the folder with your frontend app files.

您可以看到如何创建API服务器这里.

You can see how to create an API server here.

对于应用程序的入口点,您应该发送/呈现文件.

For the entry point of your application, you should send/render a file.

这可以通过以下代码完成:

This could be accomplished with the following code:

app
  .get( '/', function( req, res ) {
    res.sendFile( path.join( __dirname, 'client', 'index.html' ));
  });

每次用户在您的应用程序的根路径中请求文件时,这将发送一个静态文件.

This will send a static file every time that a user request a file at the root path of your application.

您也可以使用星号*(通配符)代替/.该符号表示,无论请求哪种路由,您都将以相同的文件/操作进行响应.

You can use the asterisk * (wildcard) instead of / too. That symbol meaning that for whatever route requested, you will respond with the same file/action.

有关响应的更多信息此处.

这些是构建应用程序应寻求的东西.

Those are the things that you should seek to build your app.

您可以在此处看到一个实现了这些功能的简单应用.

You can see a simple app with those things implemented here.

这篇关于使用express.js与脚本,css和图像一起提供html文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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