【问题标题】:Why am I getting an empty body as response from HTTP request Noe.js为什么我得到一个空正文作为来自 HTTP 请求 Node.js 的响应
【发布时间】:2020-07-10 08:05:56
【问题描述】:

所以我试图向服务器发送一个 http 请求,作为响应,我应该得到我需要的所有信息所在的正文。然后当我尝试 .parseJSON() 正文时,我得到一个异常告诉我我的身体是空的。身体不可能真的是空的,所以代码中一定有错误。 由于密码和类似的东西,我不能给你整个代码。 代码:

public addVehicle(): Promise<void>{
    return new Promise<void>((resolve, reject) => {
        const options = {
            url: [URL],
            method: "POST",
        
            headers: {
                'Content-Type': 'application/json',
                'Authorization': [user/psw],
                'token': [authToken]
            },
            body: JSON.stringify({
                'vehicleID': vehicleID,
                'externalID': externalID,
                'brandID': vehicleBrandId,
                'modelGroupID': vehicleModelId,
                'typeName': typeName,
                'segmentationID': vehicleSegmentationId,
                'categoryID': vehicleCategoryId,
                'fuelTypeID': vehicleFuelTypeId,
                'transmissionTypeID': vehicleTransmissionTypeId,
                'propulsionTypeID': vehiclePropulsionTypeId,
                'registerationDate': registerationDate,
                'powerKW': powerKW,
                'description': description
            })
            
            
            
          }

          let req = request.post(options, (err, res, body) => {
           let rawAuth = JSON.parse(body);
            console.log(body);

                resolve();
                
            })
    })
}

【问题讨论】:

    标签: node.js json httprequest


    【解决方案1】:

    尝试删除JSON.stringify()。 我假设您的接收 API 需要正文中的字段。以字符串形式发送数据将隐藏接收 API 的字段。它只会看到一个字符串对象(不确定键是什么)。

    const options = {
                url: [URL],
                method: "POST",
            
                headers: {
                    'Content-Type': 'application/json',
                    'Authorization': [user/psw],
                    'token': [authToken]
                },
                body: {
                    'vehicleID': vehicleID,
                    'externalID': externalID,
                    'brandID': vehicleBrandId,
                    'modelGroupID': vehicleModelId,
                    'typeName': typeName,
                    'segmentationID': vehicleSegmentationId,
                    'categoryID': vehicleCategoryId,
                    'fuelTypeID': vehicleFuelTypeId,
                    'transmissionTypeID': vehicleTransmissionTypeId,
                    'propulsionTypeID': vehiclePropulsionTypeId,
                    'registerationDate': registerationDate,
                    'powerKW': powerKW,
                    'description': description
                }
              }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-09-07
      • 2013-10-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多