我不久前就在某处刻了这段代码,以期再次了解它。 iv现在已经在pi上运行了一段时间,没有任何问题,但是我需要从运行Web服务器之前恢复os的备份,因为这样做我一直无法运行,所以我一直在如果我在另一台PC上运行相同的代码,则会出现语法错误(如下),效果很好。有什么想法可以让我全神贯注吗?
另外,我不知道$是jquery的意思吗?
错误
etc/server/app.js:10
console.log(`${req.method} ${req.url}`);
^
SyntaxError: Unexpected token ILLEGAL
at Module._compile (module.js:439:25)
at Object.Module._extensions..js (module.js:474:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:312:12)
at Function.Module.runMain (module.js:497:10)
at startup (node.js:119:16)
at node.js:906:3
网卡代码
var http = require('http').createServer(handler); //require http server, and create server with function handler()
const path = require('path');
const url = require('url');
var fs = require('fs'); //require filesystem module
var io = require('socket.io')(http) //require socket.io module and pass the http object (server)
http.listen(3000); //listen to port 8080
function handler (req, res) { //create server
console.log(`${req.method} ${req.url}`);
const parsedUrl = url.parse(req.url);
// extract URL path
let pathname = `.${parsedUrl.pathname}`;
// maps file extention to MIME types
const mimeType = {
'.ico': 'image/x-icon',
'.html': 'text/html',
'.js': 'text/javascript',
'.json': 'application/json',
'.css': 'text/css',
'.png': 'image/png',
'.jpg': 'image/jpeg',
'.wav': 'audio/wav',
'.mp3': 'audio/mpeg',
'.svg': 'image/svg+xml',
'.pdf': 'application/pdf',
'.doc': 'application/msword',
'.eot': 'appliaction/vnd.ms-fontobject',
'.ttf': 'aplication/font-sfnt'
};
fs.exists(pathname, function (exist){
if(!exist){
//file not found, return 404
res.writeHead(404, {'Content-Type': 'text/html'});
return res.end("404 Not Found");
}
//if directory, return index.html
if(fs.statSync(pathname).isDirectory()){
pathname += '/index.html';
}
//read file
fs.readFile(pathname, function(err, data){
if(err){
res.writeHead(500, {'Content-Type': 'text/html'});
return res.end("500 Error getting file.");
}else{
const ext = path.parse(pathname).ext;
res.setHeader('Content-type', mimeType[ext] || 'text/plane');
res.end(data);
}
})
});
}
答案 0 :(得分:1)
console.log(
$ {req.method} $ {req.url} );
这是用JavaScript进行字符串隐藏的新方法。您正在尝试创建一个带有两个javascript变量的字符串,它们之间有空格。这只是在终端上显示一些信息,您可以删除它并继续。
答案 1 :(得分:1)
这是ES6 +模板文字:
${req.method} ${req.url}
。
在其他语言中也称为“字符串插值”。它与jQuery无关。进一步了解here。
在这种情况下,它只是将请求方法和请求URL打印到控制台。类似于:"GET http://localhost:3000/posts"
。您可以将其视为在命令行中的日志记录请求。
最有可能出问题的是您正在使用不支持它的较旧版本的Node。在终端中运行以下命令:
node -v
结果是否等于或小于0.12.18?如果这样的话,那太老了。
存在以下解决方案:
您可以完全删除该行,因为该行仅打印到控制台,并且以编程方式没有实际效果(除非您实际上需要查看其打印内容)。
您还可以将其更改为旧的串联字符串连接样式,如下所示:
console.log(req.method + ' ' + req.url)
我个人建议将您的节点版本升级到最新的LTS版本。