我正在使用节点在本地主机上创建服务器。
通过本地主机访问页面时,无法通过css fontface加载字体。
在同一个文件夹中,我有一个test.html页面,当直接访问该页面时效果很好。 (不是通过本地主机。)所以我想我的问题来自serve.js文件。
我的字体是公共/字体。我的index.html也公开,而我的CSS在public / css中。
这里是 :
var http = require('http');
var fs = require('fs');
var path = require('path');
var port = process.env.PORT || 1881;
http.createServer(function (request, response) {
console.log('request starting...');
var filePath = '.' + request.url;
if (filePath == './')
filePath = './public/index.html';
var extname = path.extname(filePath);
var contentType = 'text/html';
switch (extname) {
case '.js':
contentType = 'text/javascript';
break;
case '.css':
contentType = 'text/css';
break;
case '.json':
contentType = 'application/json';
break;
case '.png':
contentType = 'image/png';
break;
case '.jpg':
contentType = 'image/jpg';
break;
case '.wav':
contentType = 'audio/wav';
break;
case '.woff2':
contentType = 'application/font-woff2';
break;
case '.woff':
contentType = 'application/font-woff';
break;
}
fs.readFile(filePath, function(error, content) {
if (error) {
if(error.code == 'ENOENT'){
fs.readFile('./404.html', function(error, content) {
response.writeHead(200, { 'Content-Type': contentType });
response.end(content, 'utf-8');
});
}
else {
response.writeHead(500);
response.end('Sorry, check with the site admin for error: '+error.code+' ..\n');
response.end();
}
}
else {
response.writeHead(200, { 'Content-Type': contentType });
response.end(content, 'utf-8');
}
});
}).listen(port);
console.log("Server Running on "+port+".\nLaunch http://localhost:"+port);
好的,所以问题不是来自节点,而是来自手写笔吗?如果我正在这样做:
@font-face
font-family Knockout
src url(../font/Knockout-HTF28-JuniorFeatherwt.woff2),url(../font/Knockout-HTF28-JuniorFeatherwt.woff)
如果我这样做,它会起作用:
@font-face
font-family Knockout
src url(../font/Knockout-HTF28-JuniorFeatherwt.woff2) format(woff2),url(../font/Knockout-HTF28-JuniorFeatherwt.woff) format(woff)
没用...
任何想法 ?
最佳答案
下载网络字体并按以下方式使用它们:
@font-face {
font-family: "Open Sans";
src: url("/fonts/OpenSans-Regular-webfont.woff2") format("woff2"),
url("/fonts/OpenSans-Regular-webfont.woff") format("woff");
}
您可以将整个路径放在URL中,因为有时在localhost上,它们只能那样工作。