简体   繁体   English

节点js服务器`${req.method} ${req.url}`

[英]node js server `${req.method} ${req.url}`

I nicked this code from somewhere a while ago with the idea of coming back to understand it some more.不久前,我从某个地方删除了这段代码,并希望回来进一步了解它。 iv been running it on a pi for a while now with no issues but I needed to restore a backup of the os from before when I had the web server running and since doing so I haven't been able to get it running I keep getting a syntax error (below) if I run the same code on another pc it works fine. iv 已经在 pi 上运行它一段时间了,没有任何问题,但我需要从之前在运行 Web 服务器时恢复操作系统的备份,自从这样做以来,我一直无法让它运行,我一直在得到如果我在另一台电脑上运行相同的代码,则出现语法错误(如下),它工作正常。 any idea where I can look im all out of idea?知道我可以在哪里看我完全没有想法吗?

also, I don't know what the $ means is it jquery?另外,我不知道 $ 是什么意思是 jquery?

ERROR错误

 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

NICKED CODE昵称

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);
            }
        })
  });
}

This is a ES6+ Template Literal: ${req.method} ${req.url} .这是一个 ES6+ 模板文字: ${req.method} ${req.url}

Also known in other languages as "string interpolation".在其他语言中也称为“字符串插值”。 It has nothing to do with jQuery.它与 jQuery 无关。 See more on it here .此处查看更多信息

In this case it is just printing the request method and the request URL to the console .在这种情况下,它只是将请求方法和请求 URL 打印到控制台。 Something like: "GET http://localhost:3000/posts" .类似于: "GET http://localhost:3000/posts" You can think of it as logging requests in the command line.您可以将其视为在命令行中记录请求。

What has mostly likely gone wrong is you are using an older version of Node that does not support it.最有可能出错的是您使用的是不支持它的旧版 Node。 run the following in your terminal:在终端中运行以下命令:

node -v

is the result 0.12.18 or less?结果是 0.12.18 还是更少? if so that's too old.如果是这样,那就太旧了。

the following solutions exist:存在以下解决方案:

  • You can upgrade your version of node您可以升级您的节点版本

  • You can just remove the line entirely since it only prints out to the console and has no actual effect programmatically (unless you actually need to see what it's printing).您可以完全删除该行,因为它只打印到控制台并且没有以编程方式产生的实际效果(除非您确实需要查看它正在打印的内容)。

  • You can also change it to the older concatenated style of string joining like so:您还可以将其更改为较旧的字符串连接样式,如下所示:

    console.log(req.method + ' ' + req.url)

Personally I'd recommend upgrading your version of node to the latest LTS version.我个人建议将您的节点版本升级到最新的 LTS 版本。

console.log(`${req.method} ${req.url}`);

This is a new way of creating strings in JavaScript.这是一种在 JavaScript 中创建字符串的新方法。 The piece of code is trying to log something to the terminal: a string with two JavaScript variables and a space in between them.这段代码试图将某些内容记录到终端:一个字符串,其中包含两个 JavaScript 变量和它们之间的空格。 It can probably be safely removed, and everything will function the same.它可能可以安全地移除,并且所有功能都将相同。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM