Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Axios to fetch XML Data

I'm relatively new to making REST API calls.

I have a form that the user fills out which include first name, last name, department, and start date.

I learned about Axios and this is what I'm using my in my React application. My current code looks like this:

    axios.get('MyAPILocationHere/users', {
        params: {
            firstName: this.state.firstName,
            lastName: this.state.lastName,
            departmentCode: this.state.department,
        }
    })
        .then(function (response) {
            console.log(response);
        })
        .catch(function (error) {
            console.log(error);
        })
        .then(function () {
            // always executed
        });  

However for my school project the Web API is using .NET Framework. And to get the response results it needs to be something like this:

http://rdc-servernamehere-vm:6001/api/users/nameLast/HANKS/nameFirst/TOM/departmentCode/MATH

When I view that link, it's also an XML file. How do I change my current code to pass my parameters to be able to get the response needed.

like image 393
hisusu32 Avatar asked May 25 '26 01:05

hisusu32


1 Answers

axios.get(`http://rdc-servernamehere-vm:6001/api/users/nameLast/${this.state.firstName}/nameFirst/${this.state.lastName}/departmentCode/${this.state.department}`
   })
    .then(function (response) {
        console.log(response); // this will print xml data structure
    })
    .catch(function (error) {
        console.log(error);
    })
    .then(function () {
        // always executed
    });  

And you should import xml to json conversion library at the top.

const convert = require("xml-js");
...
function (response) {
   console.log(response); // this will print xml data structure
   const data = JSON.parse(
    convert.xml2json(response.data, { compact: true, spaces: 2 })
  );
  this.setState({ userList: data  }); // you can use this.state.userList to view users
}