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
651 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 Reply

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

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

...