Node.js公共静态文件夹以utf-8字符集来服务js [英] Node.js public static folder to serve js with utf-8 charset

查看:172
本文介绍了Node.js公共静态文件夹以utf-8字符集来服务js的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用node.js并表示将静态JavaScript文件提供给单页应用程序。
在node.js服务器代码中,我使用express.static来允许公共访问文件夹

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/'));

在客户端,我使用 $。getScript 获取存储在公用文件夹中的JavaScript文件,例如:

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

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

当我尝试获得一些带有重音符或一些UTF-8特殊字符的JavaScript文件时得到奇怪的字符,而不是我想要的。

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?

推荐答案

使用node.js提供静态文件的最简单方法是什么?给了我静态插入自己的中间件的提示。

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.

下面的代码发现 *。js 文件,并将字符集设置为utf-8。

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

这篇关于Node.js公共静态文件夹以utf-8字符集来服务js的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆