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
624 views
in Technique[技术] by (71.8m points)

javascript - Node.js public static folder to serve js with utf-8 charset

I′m using node.js and express to serve static JavaScript files to a single page application. In the node.js server code I use express.static to allow public access folder

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

In the client side, I use $.getScript to get the JavaScript files stored in the public folder, for example:

$.getScript("js/init.js");

When I try to get some JavaScript files that have letters with accents or some UTF-8 special character I get strange characters instead of what I want.

Is there any way to set the charset when I define the public folder?

See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

An answer from What's the simplest way to serve static files using node.js? gave me the hint of inserting your own middleware before static.

The code below finds *.js files and sets the charset to utf-8.

app.use(function(req, res, next) {
  if (/.*.js/.test(req.path)) {
    res.charset = "utf-8";
  }
  next();
});
app.use(express.static(__dirname + '/public/'));

After doing this, look for the following response header.

Content-Type: application/javascript; charset=utf-8

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

...