繁体   English   中英

Axios - 从响应对象中获取请求 URI 数据

[英]Axios - get request URI data from the response object

所以,我正在尝试将节点项目从使用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));

我对response.request.uri未定义

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

您可以通过访问response.config.urlresponse.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));

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'
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM