您的位置:首页 > Web前端 > HTML

response.write()方法将指定的字符创输出到html页面时遇到的问题

2017-04-25 12:02 483 查看
逻辑描述:

index.html:

<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<title>首页</title>
<link rel="stylesheet" href="../public/css/typo.css">
<style>
body{
background-color: #3a4563;
}
#login{
margin:230px auto auto;
/*background: #ffd5d5;*/
width: 250px;
height:250px;
/*border:1px solid green;*/
/*-webkit-border-radius: 4px;*/
/*-moz-border-radius: 4px;*/
/*border-radius: 4px;*/
text-align: center;
}
#username,#password{
padding-left:8px;
width:94%;
margin-top:20px;
height:30px;
-webkit-border-radius: 4px;
-moz-border-radius: 4px;
border-radius: 4px;
}
#button{
margin-top: 20px;
webkit-display:flex;
display: flex;
justify-content:space-around;
}
#button span {
cursor:pointer;
padding:0 44px;
display: inline-block;
color: #ffffff;
font-size: 16px;
line-height: 30px;
-webkit-border-radius: 4px;
-moz-border-radius: 4px;
border-radius: 4px;
text-decoration: none;
background-color: #667cdf;
}
</style>
<body>
<div id="login">
<form action="">
<input id="username" type="text" name="username" placeholder='请输入用户名'>
<br>
<input id="password" type="password" name="password">
<br>
<div id="button">
<span class=
4000
"login">登录</span >
<span class="reg">注册</span >
</div>
</form>
</div>
</body>
</html>
<script src="../public/js/jquery.js"></script>
<script src="../public/js/index.js"></script>


通过fs.readSynce()方法取到的index.html页面的内容赋值给变量
body


然后:

response.writeHead(200,{'Content-Type':'text/html'});//注意这里的html,如果为plain则不会显示html,会输出.html文件中的字符串
response.write(body);
response.end();


这样运行后会报错:



查看后发现:



外联的js和css文件都没有成功返回相应的数据。

原因:

这是因为这段代码中规定的’Content-Type’都是’text/html’类型。而css和js也必须得按照相应的Content-Type类型加载才能成功。

另附不同文件对应的不同类型:

"html" : "text/html",
"css"  : "text/css",
"js"   : "text/javascript",
"json" : "application/json",
"ico"  : "image/x-icon",
"gif"  : "image/gif",
"jpeg" : "image/jpeg",
"jpg"  : "image/jpeg",
"png"  : "image/png",
"pdf"  : "application/pdf",
"svg"  : "image/svg+xml",
"swf"  : "application/x-shockwave-flash",
"tiff" : "image/tiff",
"txt"  : "text/plain",
"wav"  : "audio/x-wav",
"wma"  : "audio/x-ms-wma",
"wmv"  : "video/x-ms-wmv",
"xml"  : "text/xml"


如何做:

既然知道了原因我们应该如何做呢?我们需要搭建一个静态文件处理器,实现加载不同文件按不同的类型来加载。可以参开我的github。切换到lesson2分支。static-server文件夹下的static-load-server.js和static-server.js为主要代码。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  res-write
相关文章推荐