Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
667 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 Answer

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>   

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...