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();
});
};
它与JSON.stringify("hello":"world");
之类的东西完美配合。但是,当我尝试使用需要存储的数据(时间更长)时,它不会向API发送任何内容。提前谢谢!
答案 0 :(得分:0)
您的categories
变量存在竞争条件。如果某些外部代码在加载模块后快速调用putCat()
,则categories
数据可能尚未可用。
如果您有异步模块加载要做的事情,那么您应该公开一个返回promise的模块构造函数,然后您可以在该promise之后执行putCat()
。