Search code examples
phpnode.jsxmlhttprequest

NodeJs http request send api key in xml


This is the original PHP version of the code as sample =>

$curl = curl_init();
curl_setopt($curl, CURLOPT_HEADER, false);
curl_setopt($curl, CURLOPT_POST, TRUE);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);

///////////////////////////////////////////////////////////////////
/// login
$request='<?xml version="1.0" encoding="UTF-8" ?>
            <Params>
                <ApiKey>abc123</ApiKey>
            </Params>';
            
curl_setopt($curl, CURLOPT_URL, "https://api.unas.eu/shop/login");
curl_setopt($curl, CURLOPT_POSTFIELDS,$request);
$response = curl_exec($curl);
$xml=simplexml_load_string($response);
$token=(string)$xml->Token;

I wrote it based on the nodejs documentation. I also google the solution but not found and answer. Why the script is not able to connect to the unas server?

const express = require("express");
const https = require("https");

const app = express();

const postData = '<?xml version="1.0" encoding="UTF-8" ?>'+
        '<Params>' +
        '<ApiKey>abc123</ApiKey>' +
        '</Params>';

const options = {
    protocol:'https:',
    host: "api.unas.eu/shop",
    path: "/login",
    method: "POST",
    headers:{
        'Content-Type': 'application/xml',
        'Content-Length': Buffer.byteLength(postData)
    }
};

const req = https.request(options, (res) => {
    console.log('statusCode:', res.statusCode);
    console.log('headers:', res.headers);
  
    res.on('data', (d) => {
      process.stdout.write(d);
    });
  });
  
  req.on('error', (e) => {
    console.error(e);
  });
  req.end();

The response:

Error: getaddrinfo ENOTFOUND api.unas.eu/shop
    at GetAddrInfoReqWrap.onlookup [as oncomplete] (dns.js:67:26) {
  errno: -3008,
  code: 'ENOTFOUND',
  syscall: 'getaddrinfo',
  hostname: 'api.unas.eu/shop'

Could you help me to figure out why it is not working? Thanks in advance.


Solution

  • Hostname should not contain path:

    Here is the fix:

    const options = {
        protocol:'https:',
        host: "api.unas.eu",
        path: "/shop/login",
        method: "POST",
        headers:{
            'Content-Type': 'application/xml',
            'Content-Length': Buffer.byteLength(postData)
        }
    };
    

    Another concern: You are not passing the post data correctly:

    const req =...
    
    req.write(postData);//send post data to the request
    
    req.on('error', (e) => {
        console.error(e);
    });
    req.end();