首页 > 解决方案 > 如何将我的变量分配给我的 API 的字符串响应?

问题描述

我正在向 Python 烧瓶 api 发送一个发布请求。我正在返回 200 并且响应的正文正确记录在控制台中。但是,当我尝试将它传递给“响应”变量以存储它未分配的变量时。

我试图记录响应变量并查看实际传递给它的内容。如果我尝试在请求调用中将它记录到控制台,它会显示它成功地有一个字符串。但是当我将它记录到请求之外的控制台时,它显示为未定义?

这是我的 Node.js 正在调用

function handleMessage(sender_psid, received_message) {

let response;

request({
  "uri": "http://localhost:8090/givenMessage",
  "method": "POST",
  "json": received_message
}, (err, res, body) => {
  if (!err) {
    console.log('message sent to python!')
    console.log(typeof body)
    var string = JSON.stringify(body);
    var objectValue = JSON.parse(string);
    response = body; //parse the json body to string keep body in
  } else {
    console.error("Unable to send message to python:" + err);
  }
});


// Check if the message contains text
/*if (received_message.text) {    

  // Create the payload for a basic text message
  response = {
    "text": `You sent the message: "${received_message.text}".`
  }
}  */

// Sends the response message
callSendAPI(sender_psid, response);    
}

这是我的 python 后处理程序

from flask import Flask
from flask import request

app = Flask(__name__) #create the app server to recieve post

@app.route('/givenMessage', methods = ['POST'])
def postJsonHandler():
    print (request.is_json)
    content = request.get_json()
    print (content)
    return 'JSON posted'

 app.run(host = '0.0.0.0', port = 8090)

现在,当我将响应变量传递给 callSendAPI 方法时,它只是未定义。我希望它从我的 python post 调用中输出字符串 'JSON posted'

标签: pythonnode.jsjsonrest

解决方案


对不起,我回答了。发布请求很慢,因此响应变量没有时间分配。它是异步调用的。我只是将我的方法放在 if 语句中以等待发布响应


推荐阅读