简体   繁体   中英

error using nodejs to do http post request

I have followed some instructions to do http request in nodejs and I am doing it in TypeScript in the following way:

code that calls the function to do http post call:

const getCaseInfoRequest: GetCaseInfoRequest = {
            emailAddress: 'some-email-address@amazon.com'
        };

        makeCardinalCall('/SalesforceCaseService/1.0/GetCaseInfoFromEmail', getCaseInfoRequest, process.env.STAGE)
            .then((data) => {
                ...
            }).catch(...);

the function that does http post call:

export function makeCardinalCall(path: string, requestBody: GetCaseInfoRequest, stage?: string) {
   return new Promise((resolve, reject) => {
      const data = JSON.stringify(requestBody);

      const options: http.RequestOptions = {
         host: 'my-service.google.com',
         port: 443,
         path: path,
         method: 'POST',
         headers: {
            'Content-Type': 'application/json',
            'Content-Length': data.length,

         }
      };

      const req = http.request(options, (res: http.IncomingMessage) => {
         res.setEncoding("utf8");
         
         let data = '';
         res.on('data', chunk => {
            data += chunk;
         });
         res.on('end', () => {
            resolve(data);
         })
      });

      req.on('error', (e: any) => {
         reject(e);
      });

      req.end(data);
   });
}

but i always got the following error:

{"bytesParsed":0,"code":"HPE_INVALID_CONSTANT","reason":"Expected HTTP/","rawPacket":{"type":"Buffer","data":[21,0,0,0,2,1,0]}}

any hint / help would be greatly appreciated!

You're attempting to use the raw http module with an HTTPS endpoint (as evident from the port 443). The HTTP parser fails to parse the TLS bytes coming over the wire.

For your own sanity's sake, use a wrapper module for requests -- such as node-fetch ...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM