javascript - 我无法将请求正文添加到我的输出中

标签 javascript node.js request

<分区>

我从 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);

token 显示在控制台中,但输出是“Hello”而不是“Hello token”

最佳答案

在请求中调用“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
            }
        });

希望对你有帮助

关于javascript - 我无法将请求正文添加到我的输出中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51590691/

相关文章:

javascript - 如何在 postman 的响应中获取 "name"值

javascript - 公理 : How exactly to preserve session after successful authorization and send with subsequent request - while testing without browser

使用 Prisma 执行 MySQL 查询花费的时间太长

http - 是否可以在同一个 HTTP session 中有多个用户

node.js - Node Express 未发送自定义错误消息

javascript - 部分内容的预加载器

javascript - 将 <img> 替换为父元素的 CSS 背景图片(使用 jQuery 将样式与内容分开)

php - 如何创建 SOAP 1.2 请求

java - Spring 框架 3 中的 JSON-RPC

javascript - 更改 <option> 的 .html() 会将 <option> 的 selectedIndex 属性从 '-1' 重置为 '0'