【问题标题】:Using Axios to fetch XML Data使用 Axios 获取 XML 数据
【发布时间】:2021-02-21 20:08:38
【问题描述】:

我对 REST API 调用比较陌生。

我有一个用户填写的表格,其中包括名字、姓氏、部门和开始日期。

我了解了 Axios,这就是我在我的 React 应用程序中使用的。我当前的代码如下所示:

    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
        });  

但是,对于我的学校项目,Web API 使用的是 .NET Framework。为了得到响应结果,它需要是这样的:

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

当我查看该链接时,它也是一个 XML 文件。如何更改我当前的代码以传递我的参数以获得所需的响应。

【问题讨论】:

    标签: javascript asp.net reactjs api axios


    【解决方案1】:
    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
        });  
    

    你应该在顶部导入xml到json转换库。

    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
    }
    

    【讨论】:

    • 感谢您的回复是这个包裹:https://www.npmjs.com/package/xml2js还是这个https://www.npmjs.com/package/xml-js
    • @mustafaBattalogu 我现在在这里收到这个错误:'res' is not defined no-undef for this line here convert.xml2json(res.data, { compact: true, spaces: 2 })
    • hisusu32,对不起。你应该写成convert.xml2json(response.data, { compact: true, spaces: 2 })
    • 你应该使用https://www.npmjs.com/package/xml-js
    猜你喜欢
    • 2022-01-04
    • 2020-08-21
    • 2023-03-23
    • 1970-01-01
    • 1970-01-01
    • 2023-02-01
    • 1970-01-01
    • 2021-08-30
    • 1970-01-01
    相关资源
    最近更新 更多