【问题标题】:SyntaxError: Unexpected token functionSyntaxError:意外的令牌函数
【发布时间】:2017-12-06 17:08:46
【问题描述】:

通过 Node 在操作中引用聊天应用程序,并在运行 server.js 时,收到以下错误: 函数serveStatic(响应,缓存,absPath) ^^^^^^^^ SyntaxError:意外的令牌函数 在 Object.exports.runInThisContext (vm.js:73:16) 在 Module._compile (module.js:543:28) 在 Object.Module._extensions..js (module.js:580:10) 在 Module.load (module.js:488:32) 在 tryModuleLoad (module.js:447:12) 在 Function.Module._load (module.js:439:3) 在 Module.runMain (module.js:605:10) 运行时(bootstrap_node.js:418:7) 启动时(bootstrap_node.js:139:9) 在 bootstrap_node.js:533:3

这是 Server.js 代码:

var http=require('http');                             
var fs=require('fs');                                 
var path=require('path');                                                
var path= require('mime');                            
var cache={}; 




var server=http.createServer(function(request,response)
{
    var filePath=false;
    if(request.url=='/')
    {
      filePath= public/index.html;
    }
    else
    {
      'public' + request.url;
    }

    var absPath= './'+filePath;
    serveStatic(response,cache,absPath);
});

server.listen(3000,function() 
{

 console.log('Server listening to the port :3000');

});




function send404 (response )
{
    response.writeHead(404,{'Content-Type' :'text/plain'});
    response.write('Error 404: resource not found');
    response.end();
}




function sendFile(response,filePath,fileContents)
{
    response.wrieHead(200,
       {"content-type":mime.lookup(filePath)})

       };
       response.end(fileContents);

}



function serveStatic(response,cache,absPath)
{
    if(cache[absPath])
    {
    sendFile(response,absPath,cache[absPath]);
    }
    else
    {
       if(fs.exists(absPath, function(exists)))
       {
        if(exists)
        {
          fs.readFile(absPath,function(err,data))
          {
          if(err)

          {
            send404(response);
          }
          else
          {
            cache[absPath]=data;
            sendFile(response,absPath,data);
          }
          });

        }
        else
        {
        send404(response);
        }
       });
    }
}

【问题讨论】:

  • filePath= public/index.html; 缺少引号,'public' + request.url; 是一个不执行任何操作的空操作 ...
  • @AlexK。 ,现在在这个地方得到了这些缺失的引号,仍然和上图一样的错误
  • 你似乎有一些额外的随机 } 和一个随机的 ) - 正确缩进你的代码以查看问题
  • @JaromandaX - 是的,有一些额外的大括号,现在纠正它并且工作正常。

标签: javascript node.js


【解决方案1】:

这里有多余的括号:

function sendFile(response,filePath,fileContents)
{
    response.wrieHead(200,
       {"content-type":mime.lookup(filePath)})

       };
       response.end(fileContents);

}

应该这样修改:

function sendFile(response, filePath, fileContents)
{
    response.wrieHead(200, {
      "content-type": mime.lookup(filePath)
    });
    response.end(fileContents);

}

那么你的错误将被忽略。

【讨论】:

  • 谢谢,它有帮助,虽然除此之外,还有一些其他语法错误,现在运行正常,服务器监听端口:3000 :)
猜你喜欢
  • 1970-01-01
  • 2011-11-21
  • 2017-08-05
  • 2021-03-31
  • 2019-04-20
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多