gpt4 book ai didi

node.js - Google Closure Compiler 移动了 ??它给出了 302 错误

转载 作者:搜寻专家 更新时间:2023-11-01 00:26:55 24 4
gpt4 key购买 nike

我正在使用 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它说我应该向 http://closure-compiler.appspot.com/compile 发出 POST 请求...

最佳答案

您正在尝试发送 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\");"}

关于node.js - Google Closure Compiler 移动了 ??它给出了 302 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6085472/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com