3

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.

1 Answer 1

4
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
}
Sign up to request clarification or add additional context in comments.

4 Comments

thanks for your response is this the package: https://www.npmjs.com/package/xml2js or is it this one https://www.npmjs.com/package/xml-js
@mustafaBattalogu I get this error here now : 'res' is not defined no-undef for this line here convert.xml2json(res.data, { compact: true, spaces: 2 })
hisusu32, sorry. you should write as convert.xml2json(response.data, { compact: true, spaces: 2 })
you should use https://www.npmjs.com/package/xml-js package

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.