[英]Node.js - Using a for loop in Express.js to achieve multi-language/region support
我是 Node.js 的新手,对它还不是很熟悉,我想让我的网站支持多个区域; 例如英国和美国。
与其他网站类似,我想在https://website.com/us
和https://website.com/gb
等页面中分隔区域,当然,还有一个供全球查看的页面或任何您想要的页面称之为 - https://website.com
。
为此,我想出了用区域代码循环遍历数组并让 Node.js 使用从每个循环接收到的数据设置页面的想法。
ar locals = ['', 'gb', 'us']; // An array with region codes
...
for (var i = 0; i < locals.length; i++) { // Loops through the array
switch (locals[i]) { // A switch statement that sets up the data
case '': // Default view (https://website.com)
var lang = "en";
var title = "";
var href= "";
break;
case 'gb':
var lang = "en";
var title = " (United Kingdom)";
var href = "gb/";
break;
case 'us':
var lang = "en";
var title = " (United States)";
var href = "us/";
}
app.get("/" + href, function(request, response) {
response.write("<!DOCTYPE HTML>");
response.write("<html lang=\"" + lang + "\">");
response.write("<head>");
response.write("<base href=\"" + base + "\"/>");
response.write("<title>Nemalp" + title + "</title>");
... // There are scripts below that check the html tag's lang attribute and sets up the language properly.
});
};
所以有什么问题? 好吧,该页面似乎永远处于加载 state 中。 它确实加载了一些内容,但总是以GET... net::ERR_INCOMPLETE_CHUNKED_ENCODING 200 (OK)
错误结束。 并非所有脚本或网站图标有时都能正常加载,我的直觉告诉我,我刚刚所做的一切都会让我到处被解雇,哈哈……它也总是加载美国地区设置……我的错误在哪里? 我如何正确地实现我的目标? 任何形式的帮助或建议都非常感谢!
在搜索了一段时间的解决方案后,我找到了一种正确设置区域的方法。 在response.write()
函数之后,通过response.end()
function 修复了加载问题的解决方案,感谢 Alex D。
为了正确加载区域,我在代码中添加了一些额外的 arrays 几乎替换了您可以在上面看到的switch()
语句以及我的原始数组。
var href = ['', 'gb/', 'us/']; // The links that seperate the regions
var languages = ['en', 'en-GB', 'en-US']; // Used for html's lang attribute
var titles = ['', ' (United Kingdom)', ' (United States)']; // Used in the website's title
然后,我制作了一个 function 来存储这些response.write()
命令并设置页面本身。
function loadPageRegion(href, language, title) { // This function will be called later, in a loop, in order to load all the pages we want. Those attributes are used to set up the properties for the corresponding region.
function loadHome(response, languages, titles) { // Stores the response.write() functions and sets the website's title, html's lang attribute, etc.
response.set({'content-type': 'text/html; charset=utf-8' });
response.write("<!DOCTYPE HTML>");
response.write("<html lang=\"" + languages + "\">");
response.write("<head>");
response.write("<base href=\"localhost\"/>");
response.write("<title>Nemalp" + titles + "</title>");
// ...
response.end();
}
app.get("/" + href, function(request, response) { // The request
loadHome(response, language, title); // Loading the page's content
});
}
我们现在需要做的就是一个简单的循环。
for (var i = 0; i < href.length; i++) { // Iterates through the href array.
loadHomeRegion(href[i], languages[i], titles[i]); // Calls our function with the properties for the corresponding region.
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.