0

我正在阅读一本关于 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而不是将其添加为要运行的第二个函数。

有什么想法为什么会发生这种情况,以及如何修复我的代码?

4

2 回答 2

3

将您更改elseelse ifexcept last,它会抱怨,res.writeHead 200, 'Content-Type': 'text/plain'因为您在 first else 之后已经有表达 - else pathname == '/about'

于 2013-09-18T05:39:42.450 回答
1

这纯粹是一个制表符与空格的问题。确保您的编辑器不会将空格转换为制表符。此外,使用光标浏览您的代码并确保它不会跳过空白区域。问题是,虽然普通编辑器将制表符视为两个或四个空格,但 coffeescript 将其视为一个空格,因此缩进会变得混乱。

于 2013-09-18T05:35:54.003 回答