【问题标题】:Axios - get request URI data from the response objectaxios - 从响应对象中获取请求 URI 数据
【发布时间】:2021-08-14 17:50:27
【问题描述】:

所以,我正在尝试将节点项目从使用 request.js 迁移到使用 axios.js

当我使用请求包时,我可以像这样从响应对象中获取 URI 数据

request(req, (err, response) => {
  if (err) console.error(err);
  console.log(response.statusCode);
  console.log(response.request.uri);
  console.log(response.request.uri.hash);
  console.log(response.request.uri.host);
});

但是当我像这样使用 axios 时

axios(req)
  .then(response => {
    console.log(response.status);
    console.log(response.request.uri);
  })
  .catch(err => console.error(err));

undefined response.request.uri

那么,我是不是使用了错误的 axios 包,还有另一种方法可以获取我想要的信息,或者 axios 不支持该信息??

【问题讨论】:

    标签: javascript node.js request axios


    【解决方案1】:

    您可以通过访问response.config.url response.request.responseURL 来访问它,但如果您只需要URI,则需要使用正则表达式,或者您可以通过数组或字符串方法使用JS。

    示例:

    const axios require('axios');
    const url = require('url');
    
    axios(req)
      .then(response => {
        const parsedURL = url.parse(response.config.url);
        console.log(parsedURL.host);
      })
      .catch(err => console.error(err));
    

    如果您不需要解析的 URL 信息并且不想要另一个包:

    // Remove the URL Protocol (https:// & http://) using regex. 
    const removeHttpProtocol = (url) => url.replace(/(^\w+:|^)\/\//, '');
    
    axios(req)
      .then(response => {
        console.log(const responseURI = removeHttpProtocol(response.config.url);
        console.log(responseURI);
      })
      .catch(err => console.error(err));
    

    【讨论】:

      【解决方案2】:

      在您从res.config.url 获得url 后添加到@Matt Weber 的答案,您可以使用url.parse 直接解析它并从那里访问.hash .query

      例如:

      const url = require('url')
      console.dir(url.parse('protocol://host.com/?q=q1#hash'));
      
      // Outputs:
      Url {
        protocol: 'protocol:',
        slashes: true,
        auth: null,
        host: 'host.com',
        port: null,
        hostname: 'host.com',
        hash: '#hash',
        search: '?q=q1',
        query: 'q=q1',
        pathname: '/',
        path: '/?q=q1',
        href: 'protocol://host.com/?q=q1#hash'
      }
      

      【讨论】:

        猜你喜欢
        • 2020-09-01
        • 1970-01-01
        • 1970-01-01
        • 2022-01-03
        • 1970-01-01
        • 2016-08-25
        • 2020-03-22
        • 2021-05-11
        相关资源
        最近更新 更多