2011-05-22 65 views
2

我使用的是0.4.7的NodeJS提出请求,这是我的代码:Google Closure编译器移动了?它给人一种显示302错误

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它说我suposed使POST请求http://closure-compiler.appspot.com/compile ......

回答

5

您正在尝试发送JSON数据:

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

谷歌关闭编译器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\");"}