2

我正在使用 nodejs 0.4.7 发出请求,这是我的代码:

var post_data = JSON.stringify({  
    'compilation_level' : 'ADVANCED_OPTIMIZATIONS',  
    'output_format': 'json',
      'warning_level' : 'QUIET',
      'js_code' : code
});

var post_options = {  
    host: 'closure-compiler.appspot.com',  
    port: '80',  
    path: 'compile',  
    method: 'POST',  
    headers: {  
        'Content-Type': 'application/x-www-form-urlencoded',  
        'Content-Length': post_data.length  
    }  
}; 

var post_req = http.request(post_options, function(res) {  
    res.setEncoding('utf8');  
    res.on('data', function (chunk) {  
        console.log('Response: ' + chunk);  
    });  
});

post_req.write(post_data);  
post_req.end();

我得到的回应是

Response: <HTML><HEAD><meta http-equiv="content-type" content="text/html;charset=utf-8">
<TITLE>302 Moved</TITLE></HEAD><BODY>
<H1>302 Moved</H1>
The document has moved
<A HREF="http://www.google.com/">here</A>.
</BODY></HTML>

为什么会这样?我究竟做错了什么 ?在教程中它说我应该向http://closure-compiler.appspot.com/compile发出 POST 请求...

4

1 回答 1

5

您正在尝试发送 json 数据:

var post_data = JSON.stringify({  
    'compilation_level' : 'ADVANCED_OPTIMIZATIONS',  
    'output_format': 'json',
      'warning_level' : 'QUIET',
      'js_code' : code
});

Google Closure Compiler API 需要标准的表单数据,所以你想使用它querystring。您还需要指出您想要的输出格式(我假设的编译代码),如他们的文档所指定:

var post_data = querystring.stringify({  
    'compilation_level' : 'ADVANCED_OPTIMIZATIONS',  
    'output_format': 'json',
    'output_info': 'compiled_code',
      'warning_level' : 'QUIET',
      'js_code' : code
});

路径最好像这样声明:

path: '/compile', 

这是概念代码的完整证明:

var http = require('http');
var querystring = require('querystring');

var code ="// ADD YOUR CODE HERE\n" +
"function hello(name) {\n" +
" alert('Hello, ' + name);\n" +
"}\n" +
"hello('New user');\n";

var post_data = querystring.stringify({  
    'compilation_level' : 'ADVANCED_OPTIMIZATIONS',  
    'output_format': 'json',
    'output_info': 'compiled_code',
      'warning_level' : 'QUIET',
      'js_code' : code
});

var post_options = {  
    host: 'closure-compiler.appspot.com',  
    port: '80',  
    path: '/compile',  
    method: 'POST',  
    headers: {  
        'Content-Type': 'application/x-www-form-urlencoded',  
        'Content-Length': post_data.length  
    }  
}; 

var post_req = http.request(post_options, function(res) {  
    res.setEncoding('utf8');  
    res.on('data', function (chunk) {  
        console.log('Response: ' + chunk);  
    });  
});

post_req.write(post_data);  
post_req.end();

运行它node.js会产生以下结果:

$ node test.js 
Response: {"compiledCode":"alert(\"Hello, New user\");"}
于 2011-05-22T01:59:11.347 回答