SyntaxError:意外的令牌>

时间:2016-02-18 19:09:08

标签: javascript

我刚安装了node并试图编写并运行一些程序。 当我尝试这个示例progra时,我收到一个错误。

也许node和npm安装不正确? 也许应该安装一些必要的包?

const http = require('http');
const net = require('net');
const url = require('url');

// Create an HTTP tunneling proxy
var proxy = http.createServer( (req, res) => {
    res.writeHead(200, {'Content-Type': 'text/plain'});
    res.end('okay');
});

proxy.on('connect', (req, cltSocket, head) => {
    // connect to an origin server
    var srvUrl = url.parse(`http://${req.url}`);
    var srvSocket = net.connect(srvUrl.port, srvUrl.hostname, () => {
        cltSocket.write('HTTP/1.1 200 Connection Established\r\n' + 'Proxy-agent: Node.js-Proxy\r\n' + '\r\n');
        srvSocket.write(head);
        srvSocket.pipe(cltSocket);
        cltSocket.pipe(srvSocket);
    });
});

为什么会出现以下错误?

var proxy = http.createServer( (req, res) => {
                                       ^
SyntaxError: Unexpected token >
    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 Function.Module.runMain (module.js:497:10)
    at startup (node.js:119:16)
    at node.js:902:3 ##

1 个答案:

答案 0 :(得分:1)

试试这样;

   var requestListener = function (req, res) {
       res.writeHead(200, {'Content-Type': 'text/plain'});
       res.end('okay');
    }

    var proxy = http.createServer(requestListener);