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

Joã*_*imo 2 google-closure google-closure-compiler node.js

我正在使用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();
Run Code Online (Sandbox Code Playgroud)

我得到的回应是

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>
Run Code Online (Sandbox Code Playgroud)

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

ont*_*ia_ 5

您正在尝试发送json数据:

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

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
});
Run Code Online (Sandbox Code Playgroud)

路径更好地声明如下:

path: '/compile', 
Run Code Online (Sandbox Code Playgroud)

以下是概念代码的完整证明:

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();
Run Code Online (Sandbox Code Playgroud)

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

$ node test.js 
Response: {"compiledCode":"alert(\"Hello, New user\");"}
Run Code Online (Sandbox Code Playgroud)