我正在阅读一本关于 Node.js 的书,但我尝试用 CoffeeScript 而不是 JavaScript 来学习它。
当前正在尝试将一些 CoffeeScript 编译为此 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/');
这是我的 CoffeeScript 代码:
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
逻辑设置方式有问题;当我编译时,它看起来也可能试图返回 res.end 语句,而不是将其添加为第二个要运行的函数。
有什么想法可能会发生这种情况,以及如何修复我的代码吗?
最佳答案
将您的 else
更改为 else if
除了最后一个,它会提示 res.writeHead 200, 'Content-Type': 'text/plain'
因为您在第一个 else 之后已经有了表达式 - else pathname == '/about'
关于javascript - 尝试让coffescript正确编译为 Node 服务器的javascript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18864538/