Node Beginner Book - requestHandlers

时间:2014-08-03 08:46:10

标签: node.js http

正如标题所说,我遇到了一个问题,即node.js命令提示符位于requestHandlers.js文件中。我正在按照Node Beginner Book中的指南进行操作,直到现在,本书没有任何问题 - 或者说我的代码。

我有以下输入:

index.js:

var server = require("./server");
var router = require("./router");
var requestHandlers = require("./requestHandlers");
var handle = {}
handle["/"] = requestHandlers.start;
handle["/start"] = requestHandlers.start;
handle["/upload"] = requestHandlers.upload;
server.start(router.route, handle);

server.js:

var http = require("http");
var url = require("url");
function start(route, handle) {
function onRequest(request, response) {
var pathname = url.parse(request.url).pathname;
console.log("Request for " + pathname + " received.");
route(handle, pathname);
response.writeHead(200, {"Content-Type": "text/plain"});
response.write("Hello World");
response.end();
}
http.createServer(onRequest).listen(8888);
console.log("Server has started.");
}
exports.start = start;

router.js

function route(handle, pathname) {
console.log("About to route a request for " + pathname);
if (typeof handle[pathname] === 'function') {
handle[pathname]();
} else {
console.log("No request handler found for " + pathname);
}
}
exports.route = route;

requestHandlers.js

function start() {
console.log("Request handler "start" was called.");
}
function upload() {
console.log("Request handler "upload" was called.");
}
exports.start = start;
exports.upload = upload;

我有这个输出:

" C:\ Program Files(x86)\ nodejs \ requestHandlers.js:1 console.log("请求处理程序"开始"是

SyntaxError: Unexpected identifier
    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 Module.require (module.js:364:17)
    at require (module.js:380:17)
    at Object.<anonymous> (C:\Program Files (x86)\nodejs\index.js:1:153)
    at Module._compile (module.js:456:26)
    at Object.Module._extensions..js (module.js:474:10)
    at Module.load (module.js:356:32)"

我无法真正看出问题所在。我已经按照书中的指南进行了操作,我已经从书中复制粘贴代码或者自己编写代码。我已经对错误的代码进行了双重检查,但没有找到任何错误。我记得我用过`\'功能\&#39;例如,在node.js中输入代码时,代码中不会出现任何错误。

所以任何帮助都会受到赞赏!

感谢。

1 个答案:

答案 0 :(得分:2)

您在JavaScript中混合了不同的字符串标记。

function start() {
   console.log("Request handler "start" was called.");
}
function upload() {
  console.log("Request handler "upload" was called.");
}

您可以使用“作为字符串的开头和结尾,但类似"Request handler "start" was called."

无效,因为您在“开始处终止字符串并在”被称为时开始一个新字符串。

如果startupload是变量,只需将字符串连接起来就像这样:

"Request handler " + start + " was called."

或将您的字符串更改为以下内容:

"Request handler 'start' was called."

或删除“围绕开始和上传。