我正在阅读一本关于 node.js 的书,但我试图用咖啡脚本而不是 javascript 来学习它。
目前试图让一些咖啡脚本编译到这个 js 作为路由演示的一部分:
var http = require('http'),
url = require('url');
http.createServer(function (req, res) {
var pathname = url.parse(req.url).pathname;
if (pathname === '/') {
res.writeHead(200, {
'Content-Type': 'text/plain'
});
res.end('Home Page\n')
} else if (pathname === '/about') {
res.writeHead(200, {
'Content-Type': 'text/plain'
});
res.end('About Us\n')
} else if (pathname === '/redirect') {
res.writeHead(301, {
'Location': '/'
});
res.end();
} else {
res.writeHead(404, {
'Content-Type': 'text/plain'
});
res.end('Page not found\n')
}
}).listen(3000, "127.0.0.1");
console.log('Server running at http://127.0.0.1:3000/');
这是我的咖啡脚本代码:
http = require 'http'
url = require 'url'
port = 3000
host = "127.0.0.1"
http.createServer (req, res) ->
pathname = url.parse(req.url).pathname
if pathname == '/'
res.writeHead 200, 'Content-Type': 'text/plain'
res.end 'Home Page\n'
else pathname == '/about'
res.writeHead 200, 'Content-Type': 'text/plain'
res.end 'About Us\n'
else pathname == '/redirect'
res.writeHead 301, 'Location': '/'
res.end()
else
res.writeHead 404, 'Content-Type': 'text/plain'
res.end 'Page not found\n'
.listen port, host
console.log "Server running at http://#{host}:#{port}/"
我回来的错误是:
helloworld.coffee:14:1: error: unexpected INDENT
res.writeHead 200, 'Content-Type': 'text/plain'
^^^^^^^^
这让我觉得我if...else
设置逻辑的方式有问题;当我编译时,它看起来也像是在尝试return
语句res.end
而不是将其添加为要运行的第二个函数。
有什么想法为什么会发生这种情况,以及如何修复我的代码?