Node.JS Express API-包括请求-承诺链的承诺链-ERR_INVALID_HTTP_TOKEN

时间:2020-01-30 15:06:25

标签: node.js api express promise request-promise

我拥有的链是从Sql Server检索信息,然后设置数据,然后通过邮寄发送到api。问题是我收到此 RequestError 消息,**“ TypeError [ERR_INVALID_HTTP_TOKEN]:标头名称必须是有效的HTTP令牌[” key“]”

客观

-使用ID检索数据
-格式化数据
-向带有格式数据的api发送新的单独请求
-解决从api调用返回的结果

router.js

    router.get('/request/:id', controller.data_post)
    module.exports = router

Controller.js


    exports.data_post = function(req, res) {

        ...

        RetrieveData( req.id ) //retrieves data
        .then( results => { //format data

           var obj = formatData(results);
           let body = [];
           body.push(obj);

           return body //resolve formatted data
         } //End Of Promise
        })
       .then( body => { //Send new, separate request to an api with formatted data

             var options = :{
                 method: 'POST',
                 uri: 'url',
                 headers: {
                     'key':'value',
                     'Content-Type': 'application/json'
                 },
                 body: JSON.stringify(body),
                 json:true
         }

         return option
         })
        .then( results => {
          //send results
        })
        .catch( error => {
         //error routine
        }) 
    }           


RetrieveData.js

    function RetrieveData( id ){
      const promise = new Promise((resolve, reject) => {
         ...
         resolve(data)
      }
      return promise;
    }

RequestUtility.js

    const request = require('request-promise')

    function requestutility(options) {
       return request(options)
       .then( response => {
           return response;
       }) 
       .catch( error => {
          return error;
        })
    }

当前错误

  • “名称” :“ RequestError”,
  • 消息” :“ TypeError [ERR_INVALID_HTTP_TOKEN]:标头名称必须是有效的HTTP令牌[“ key”]“,
  • 选项:对象{},
  • 回调:函数RP $ callback(err,response,body){

    • 自变量:TypeError:在严格模式函数或对其调用的自变量对象中,可能无法访问“ caller”,“ callee”和“ arguments”属性
    • 呼叫者:TypeError:在严格模式功能或对其调用的参数对象中,可能无法访问“ caller”,“ callee”和“ arguments”属性
      }

1 个答案:

答案 0 :(得分:1)

我在这里看到的问题对

  • 您不需要在request实用程序方法中返回Promise.resolve和Promise.reject。由于请求承诺会返回承诺,因此您的承诺将在成功完成时得到解决,而在出错时被拒绝。因此,您可以一起摆脱requestutility。

  • 您将结果包装在new Promise中,这不是必需的。

  • resolve( requestutility(option))不能像您期望的那样工作,因为它将解决一个承诺而不是价值。
  • 从标题中删除密钥。 我试图更新代码。看起来应该像
const request = require("request-promise");

RetrieveData(id)
  .then(results => {
    const obj = formatData(results);
    const body = [];
    body.push(obj);
    return body;
  })
  .then(body => {
    const options = {
      "method": "POST",
      "uri": "url",
      "headers": {
        "key": "value",
        "Content-Type": "application/json"
      },
      "body": JSON.stringify(body),
      "json": true
    };

    return request(options);
  })
  .then(results => {
    // send results
  })
  .catch(error => {
    // error routine
  });