Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
705 views
in Technique[技术] by (71.8m points)

node.js - res.sendfile() doesn't serve javascripts well

I want to use static file serve without any 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:

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

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

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

UPDATE:

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

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

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I guess this might help you...

in app.js file...

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.html inside the /public folder and JavaScript files in /public/javascripts, images in /public/images, css files in /public/stylesheets folder.

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

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...