谷歌闭包编译器搬了?它给出了302错误

时间:2011-05-22 01:26:41

标签: node.js google-closure-compiler google-closure

我正在使用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>

为什么会这样?我究竟做错了什么 ?在tutorial中,它表示我已向@ {3}}发出POST请求...

1 个答案:

答案 0 :(得分: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。您还需要指定所需的输出格式(我假设的编译代码),如指定的by their documentation

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\");"}