栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

Node.js-外部JS和CSS文件(仅使用node.js不表达)

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Node.js-外部JS和CSS文件(仅使用node.js不表达)

您的代码有几个问题。

  1. 您的服务器没有指定要监听的端口,将无法运行。
  2. 正如Eric指出的那样,您的案例条件将失败,因为URL中未显示“ public”。
  3. 您在js和CSS响应中引用的变量“ content”不存在,应该是“ data”。
  4. 您的CSS内容类型标头应为text / css而不是text / javascript
  5. 无需在主体中指定“ utf8”。

我已经重新编写了您的代码。注意我不使用大小写/开关。如果不是这样,我宁愿简单得多,如果您愿意,可以将它们放回去。url和path模块在我的重写中不是必需的,因此已将其删除。

var http = require('http'),    fs = require('fs');http.createServer(function (req, res) {    if(req.url.indexOf('.html') != -1){ //req.url has the pathname, check if it conatins '.html'      fs.readFile(__dirname + '/public/chatclient.html', function (err, data) {        if (err) console.log(err);        res.writeHead(200, {'Content-Type': 'text/html'});        res.write(data);        res.end();      });    }    if(req.url.indexOf('.js') != -1){ //req.url has the pathname, check if it conatins '.js'      fs.readFile(__dirname + '/public/js/script.js', function (err, data) {        if (err) console.log(err);        res.writeHead(200, {'Content-Type': 'text/javascript'});        res.write(data);        res.end();      });    }    if(req.url.indexOf('.css') != -1){ //req.url has the pathname, check if it conatins '.css'      fs.readFile(__dirname + '/public/css/style.css', function (err, data) {        if (err) console.log(err);        res.writeHead(200, {'Content-Type': 'text/css'});        res.write(data);        res.end();      });    }}).listen(1337, '127.0.0.1');console.log('Server running at http://127.0.0.1:1337/');


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/484672.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号