我从node.js开始,我正在尝试做一个简单的请求。我正在使用“请求”:“ ^ 2.87.0”
output = "Hello ";
const h = {'content-type': 'application/json'};
const u = weburl;
const b = JSON.stringify({
"username" : user,
"password" : psw
});
request.post({
headers : h,
url : u,
body : b
},function(error,response,body){
if (error)
output+= error;
else {
var jsonbody = JSON.stringify(body); //jsonbody = "\"token\""
jsonbody = jsonbody.substr(3,jsonbody.length-4); // jsonbody = token
console.log(jsonbody);
output += jsonbody;
}
});
send_message(output);
令牌显示在控制台中,但输出为“ Hello”而不是“ Hello token”
答案 0 :(得分:2)
在请求中调用“ send_message()
”,
由于js send_message()
的异步特性,在完成请求之前被调用
喜欢:
output = "Hello ";
const h = {'content-type': 'application/json'};
const u = weburl;
const b = JSON.stringify({
"username" : user,
"password" : psw
});
request.post({
headers : h,
url : u,
body : b
},function(error,response,body){
if (error)
output+= error;
else {
var jsonbody = JSON.stringify(body); //jsonbody = "\"token\""
jsonbody = jsonbody.substr(3,jsonbody.length-4); // jsonbody = token
console.log(jsonbody);
output += jsonbody;
send_message(output); //<---- here
}
});
希望这会有所帮助