2017-07-03 35 views
1

通过Node动作创建一个聊天应用程序,并在运行server.js时出现以下错误: function serveStatic(response,cache,absPath) ^^^^^^^^ SyntaxError:意外的标记函数 at Object.exports.runInThisContext(vm.js:73:16) at Module._compile(module.js:543:28) at Object.Module._extensions..js(module.js :module.js:488:32) at tryModuleLoad(module.js:447:12) at Function.Module._load(module.js:439:3) at Module在Module.load(module.js:488:32) .runMain(module.js:605:10) at run( bootstrap_node.js:418:7) 在启动时(bootstrap_node.js:139:9) 在bootstrap_node.js:533:3SyntaxError:意外的令牌功能

这里是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); 
     } 
     }); 
    } 
} 
+2

'filePath = public/index.html;'缺少引号和''public'+ request.url;'是一个没有任何操作的无效操作... –

+0

@AlexK。 ,现在在这个地方得到了这些缺失的引号,仍然是上面显示的错误 –

+0

,您似乎还有一些额外的随机'}'和一个随机') - 正确缩进代码以查看问题 –

回答

0

你必须这里额外的括号:

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

} 

然后你的错误将被解雇。

+0

谢谢,它有帮助,但除此之外,还有其他几个语法错误,现在运行良好,服务器正在侦听端口:3000 :) –