You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

NodeJS中request.get返回的body无法存入变量问题求助

解决request.get异步响应无法存入变量的问题

嘿,我明白你碰到的问题了——这其实是Node.js里异步编程的经典坑!你现在的写法里,request.get是一个异步操作:当你发起请求后,Node.js不会等着请求完成才继续往下走,而是直接执行后面的代码,而回调函数(就是你写的function(err, response, body))要等服务器返回响应后才会触发。这就导致你一开始定义的secureresponse在回调执行前还是初始值,等回调里想赋值的时候,可能你已经在别的地方用了这个变量,自然拿不到正确的body。

下面给你几个可行的解决方案,从适配你现有代码的方式,到更现代的写法都有:

方案1:用回调函数处理异步结果

修改你的tokenize函数,让它接受一个回调参数,在请求完成后把结果通过回调传递出去:

var request = require('request');
module.exports = {
  tokenize: function(text, callback){
    console.log("Request to tokenize.");
    var ServerEndpoint = 'http://localhost:3002/id/'+text;
    
    request.get(ServerEndpoint, function(err, response, body){
      if (!err && response.statusCode == 200){
        // 请求成功,把body传给回调的第二个参数
        callback(null, body);
      } else {
        // 请求失败,把错误信息传给回调的第一个参数
        const error = err || new Error("Server didn't respond.");
        callback(error, null);
      }
    });
  }
}

调用这个函数的时候,通过回调获取结果:

// 假设你的模块叫tokenModule
const tokenModule = require('./你的模块文件名.js');

tokenModule.tokenize("要处理的文本", function(err, secureresponse) {
  if (err) {
    console.error("出错了:", err);
    return;
  }
  // 这里就能拿到正确的响应body了
  console.log("服务器返回的结果:", secureresponse);
  // 在这里写处理secureresponse的逻辑
});

方案2:改用Promise/async-await(更推荐)

request库其实已经停止维护了,更推荐用axios或者node-fetch这些支持Promise的现代HTTP库,配合async-await写法,代码会更直观,像同步代码一样:

首先安装axios:

npm install axios

然后重写你的函数:

const axios = require('axios');
module.exports = {
  tokenize: async function(text){
    console.log("Request to tokenize.");
    const ServerEndpoint = `http://localhost:3002/id/${text}`;
    
    try {
      // 用await等待请求完成,拿到响应
      const response = await axios.get(ServerEndpoint);
      // 返回响应体
      return response.data;
    } catch (err) {
      console.error("请求出错:", err);
      throw new Error("Server didn't respond.");
    }
  }
}

调用的时候,需要在async函数里使用await:

const tokenModule = require('./你的模块文件名.js');

// 定义一个async函数来调用
async function handleTokenize() {
  try {
    const secureresponse = await tokenModule.tokenize("要处理的文本");
    console.log("服务器返回的结果:", secureresponse);
    // 在这里处理结果
  } catch (err) {
    console.error("出错了:", err);
  }
}

handleTokenize();

核心思路就是:异步操作的结果不能用同步赋值的方式获取,必须通过回调、Promise或者async-await来等待结果返回后再处理。

内容的提问来源于stack exchange,提问作者Fede E.

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 09:12:37