[英]Why doesn't my http request work for long JSON string?
var http = require('http');
var qhttp = require('q-io/http');
var formidable = require('formidable');
var categories;
qhttp.read("https://api.myjson.com/bins/509wa")
.then(function (json) {
categories = JSON.parse(json).categories;
})
.then(null, console.error);
module.exports.putCat = function(req, res){
var form = new formidable.IncomingForm();
form.parse(req, function(error, fields, files){
if(error){console.log(error)}
fields["catProd"] = [];
categories.push(fields);
var dataString = JSON.stringify({categories: categories});
console.log(dataString);
var options = {
host : "api.myjson.com",
path : "/bins/509wa.json",
method: "PUT",
headers: {"Content-Type": "application/json", "Content-Length": dataString.length}
};
function callback(response){
var body = "";
response.on('data', function(chunk){
body+=chunk;
});
response.on('end', function(){
console.log('Received data: '+body);
});
}
http.request(options, callback).write(dataString);
res.end();
});
};
It works perfectly with something like JSON.stringify("hello":"world");
它与
JSON.stringify("hello":"world");
类的东西完美配合JSON.stringify("hello":"world");
. . However, when I tried with my data that needs to be stored (which is much longer), it doesn't send anything to the API.
但是,当我尝试使用需要存储的数据(更长)时,它不会向 API 发送任何内容。 Thanks in advance!
提前致谢!
You have a race condition with the categories
variable.您有
categories
变量的竞争条件。 If some external code calls putCat()
quickly after loading the module, then the categories
data may not be available yet.如果某些外部代码在加载模块后快速调用
putCat()
,则categories
数据可能尚不可用。
If you have async module loading things to do, then you should probably expose a module constructor which returns a promise and you can then do the putCat()
after that promise resolves.如果您有异步模块加载要做的事情,那么您可能应该公开一个返回承诺的模块构造函数,然后您可以在该承诺解决后执行
putCat()
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.