node.js res.sendfile() 不能很好地提供 javascripts

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18165138/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 15:16:57  来源:igfitidea点击:

res.sendfile() doesn't serve javascripts well

node.jsexpress

提问by ohadinho

I want to use static file serve withoutany rendering engine. I've tried to use:

我想使用没有任何渲染引擎的静态文件服务。我试过使用:

res.sendfile('public/index.html');

on the '/' GET route, and express middleware for static files on my route:

在 '/' GET 路由上,并在我的路由上为静态文件表达中间件:

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

BUTit seems like all of the javascripts which the client asks for are downloaded with index.html file information.

似乎客户端要求的所有 javascripts 都与 index.html 文件信息一起下载。

How can I make a successful download of the CSS/JS static files ?

如何成功下载 CSS/JS 静态文件?

UPDATE:

更新:

Here is the route for the "res.sendfile ..." :

这是“res.sendfile ...”的路线:

app.get('/*', index);

I want all of the requests to the server on any route will get index.htmland all of its JS&CSS assosiciated with.

我希望任何路由上对服务器的所有请求都将得到,index.html并且所有的 JS&CSS 都与之相关联。

回答by user2681045

I guess this might help you...

我想这可能会帮助你...

in app.jsfile...

app.js文件...

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

app.use("/styles",  express.static(__dirname + '/public/stylesheets'));
app.use("/scripts", express.static(__dirname + '/public/javascripts'));
app.use("/images",  express.static(__dirname + '/public/images'));


// development only
if ('development' == app.get('env')) {
  app.use(express.errorHandler());
}

app.get('/', function (req, res) {
      res.sendfile(__dirname + '/public/home.html');
});

save the home.htmlinside the /publicfolder and JavaScript files in /public/javascripts, images in /public/images, css files in /public/stylesheetsfolder.

home.html内部/public文件夹和 JavaScript 文件保存在/public/javascripts,图像在/public/images,css 文件在/public/stylesheets文件夹中。

In the HTML file reference should be the words you define(eg: /scripts/home.js)... like this

在 HTML 文件中引用应该是你定义的词(例如:scripts//home.js)...像这样

    <link rel="stylesheet"   type="text/css" href="/styles/home.css" >
    <script src="/scripts/home.js" type="text/javascript"></script>   

回答by user3543469

var express=require("express");

var app=express();

app.use('/', express.static(__dirname + '/website/views/'));


app.set("views",__dirname+'/website/views');


app.get("/",function(req,res){
    res.sendfile('index.html');

});

the codes above is mine.i wish to help you.

上面的代码是我的。我想帮助你。

回答by Ladmerc

Well, the simplest solution will be to move app.use(express.static(path.join(__dirname, 'public')))

嗯,最简单的解决方案是移动 app.use(express.static(path.join(__dirname, 'public')))

up before you call app.use(app.router);

在你打电话之前 app.use(app.router);

This way, the static middleware gets served before the app.get('/*', index);

这样,静态中间件在 app.get('/*', index);

回答by user2978963

Why not something like this?

为什么不是这样的?

if(req.url == '/') { // Root lookups appear to be mapped to index.html
    next();
} else {
    fname = [disk location of your website] + req.url;
    fs.open(fname, 'r', function(err, fd) {
        if(err) {
            next();
        } else {
            fs.close(fd);
            res.sendfile(fname);
        }
     });
}

回答by dc5

I've made an assumption here that your routes are declared in this order:

我在这里假设您的路线是按以下顺序声明的:

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

If this is indeed the case, then the following suggestion holds:

如果确实如此,那么以下建议成立:

The problem here is the app.get('/*', …) will intercept all requests that match, which is basically everything. Your static middleware won't get a chance at serving files.

这里的问题是 app.get('/*', ...) 会拦截所有匹配的请求,这基本上就是一切。您的静态中间件将没有机会提供文件。

If you remove that route, things should work for you as index.htmlis already in the publicdirectory and can be served by the static middleware.

如果您删除该路由,那么事情应该对您index.html有用,因为public目录中已经存在并且可以由静态中间件提供服务。

For a good explanation of how this works, see the answer to this question: node.js / express.js - How does app.router work?

有关其工作原理的良好解释,请参阅以下问题的答案:node.js / express.js - app.router 如何工作?

Update based on additions to the above question:

根据对上述问题的补充进行更新:

You've stated this as the current behavior of your server:

您已将其声明为服务器的当前行为:

it seems like all of the javascripts which the client asks for are downloaded with index.html file information.

似乎客户端要求的所有 javascripts 都与 index.html 文件信息一起下载。

You have asked the question:

你问过这个问题:

How can I make a successful download of the CSS/JS static files ?

如何成功下载 CSS/JS 静态文件?

with this requirement

有这个要求

I want all of the requests to the server on any route will get index.html and all of its JS&CSS assosiciated with.

我希望任何路由上对服务器的所有请求都将获得 index.html 及其所有的 JS&CSS。

Your question and requirement are opposed to each other. The server will send back to the client exactly what you tell/configure it to. It will either always send back index.htmlwhich is exactly what your requirement states, or it will successfully serve up both index.htmland any CSS/Javascript it references which is what your original problem statement was.

你的问题和要求是对立的。服务器将准确地将您告诉/配置的内容发送回客户端。它要么总是发回index.html您的要求所陈述的内容,要么成功地提供两者index.html以及它引用的任何 CSS/Javascript,这就是您最初的问题陈述。

In one of your comments below you've stated:

在您下面的评论之一中,您已经指出:

the reason I want to do it, is because I'm using templates, and index.html wraps each template. I'm using angular on the client, and I'm starting to realize that i'll have to use a render engine in order to achieve this. Again, my angular client defines the partial url, and when it sends the request to : '/partial/sample' I need the index.html to wrap the 'sample.html' for instance

我想这样做的原因是因为我使用了模板,并且 index.html 包装了每个模板。我在客户端上使用 angular,我开始意识到我必须使用渲染引擎才能实现这一点。同样,我的 Angular 客户端定义了部分 url,当它发送请求到:'/partial/sample' 时,我需要 index.html 来包装 'sample.html'

My assumptions based on this statement (please correct if wrong)

我基于此陈述的假设(如有错误,请更正)

  • You are using client sidetemplates
  • The files you are retrieving from the server are static (i.e., they need to be served up as isfrom the server)
  • Your routes are currently declared in this order
    1. app.use(app.router);
    2. app.use(express.static(path.join(__dirname, 'public')));
  • You are not doing any server side templating (i.e. everything is located under publicsomewhere)
  • 您正在使用客户端模板
  • 您从服务器检索的文件是静态的(即,它们需要按原样从服务器提供)
  • 您的路线当前按此顺序声明
    1. app.use(app.router);
    2. app.use(express.static(path.join(__dirname, 'public')));
  • 你没有做任何服务器端模板(即一切都位于public某处)

If these assumptions are correct, the fix is to do what I originally suggested and remove this route:

如果这些假设是正确的,则解决方法是执行我最初的建议并删除此路线:

app.get('/*', index);

If you do this (assuming your resources are referenced correctly):

如果你这样做(假设你的资源被正确引用):

  • your index.htmlwill be retrieved as is from the server via the static middleware.
  • Each css/js file you've referenced in index.html will be returned from the server via the static middleware
  • Any requests to load template files (such as sample.html) will be serviced by your static middeware and returned to the client without modification
  • index.html将通过静态中间件从服务器按原样检索。
  • 您在 index.html 中引用的每个 css/js 文件都将通过静态中间件从服务器返回
  • 任何加载模板文件(例如sample.html)的请求将由您的静态中间件提供服务,并在不加修改的情况下返回给客户端