2017-08-17 235 views
0

任何想法如何将下面的php代码示例“转化”为NodeJS中的HTTP API请求?NodeJS API HTTP POST请求身份验证

<?php 
$auth='<?xml version="1.0" encoding="UTF-8" ?> 
      <Auth> 
       <Username>...</Username> 
       <PasswordCrypt>...</PasswordCrypt> 
       <ShopId>...</ShopId> 
       <AuthCode>...</AuthCode> 
      </Auth>'; 
$params='<?xml version="1.0" encoding="UTF-8" ?> 
      <Params> 
       <Key>...</Key> 
      </Params>'; 

$curl = curl_init(); 
curl_setopt($curl, CURLOPT_HEADER, false); 
curl_setopt($curl, CURLOPT_POST, TRUE); 
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); 
curl_setopt($curl, CURLOPT_URL, "https://api.unas.eu/shop/getOrder"); 
curl_setopt($curl, CURLOPT_POSTFIELDS,"auth=".$auth."&params=".$params); 
$response = curl_exec($curl); 

echo $response; 
?> 

参数必须以(auth,params,XML)POST变量发送。

许多THX提前,

亲切的问候, 索尔特

回答

0

浏览器,你可以很容易做到的请求,并使用解析XML的jQuery:

$.ajax({ 
    url: "https://mail.google.com/mail/feed/atom/", 
    dataType: "xml", 
    success: function(data) { 
     console.log(data); 
    } 
}); 

或者,如果你只是想解析XML可以使用DOMParser():

parser = new DOMParser(); 
xmlDoc = parser.parseFromString(txt, "text/xml"); 

With Node.js它有点复杂。 Javascript熟悉JSON(JavaScript对象表示法),因此XML解析器中没有构建。你必须需要某种形式的XML解析器模块,例如:

  1. libxmljs
  2. xml-stream
  3. xmldoc
  4. cheerio - 实现了核心的jQuery的XML(和HTML)

一个子集完整示例:

var fetch = require('node-fetch'), //implements Fetch API for making requests 
    libxmljs = require("libxmljs"); //xml parser, read about it here: https://github.com/libxmljs/libxmljs 

fetch('http://SOME_PAGE.com/data?type=xml') 
.then((res) => res.text()) 
.then((xml) => { 
    var xmlDoc = libxmljs.parseXml(xml); 

    //do something with xmlDoc 

});