【问题标题】:filtering an axios response过滤 axios 响应
【发布时间】:2021-10-17 15:25:40
【问题描述】:

我提出了一个 axios 请求,我收到大量数据返回,我不知道如何过滤它。

这是我的代码

await axios(config)
.then(function (response) {
const authToken = response
console.log(authToken)  
})
.catch(function (error) {
  console.log(error);
});

这只是响应的一小部分

<form class="edit_checkout" action="/942252/checkouts/536693bdcfc6f7344d1a5b500b546824" accept-charset="UTF-8" method="post"><input type="hidden" name="_method" value="patch" /><input type="hidden" name="authenticity_token" value="hFK7eHqqzlwcmpu2o3eeqVsqiNzruv8w0IPsDUQdDExwN-cdMlEsEWqYGbabkMvUf_rs_FnmmzY6H1MiSdIMOw" />\n' +
    '  <input type="hidden" name="step" value="contact_information" />\n' 

我希望通过表单类来定位这部分响应,并且我需要与 value 属性关联的字符串。我该怎么做?

【问题讨论】:

  • 只是为了澄清我需要很长字符串的值

标签: javascript node.js axios request


【解决方案1】:

使用 DOMParser 解析响应 - 然后您可以使用 querySelector

await axios(config)
.then(function(response) {
    const parser = new DOMParser;
    const doc = parser.parseFromString(response, "text/html");
    const input = doc.querySelector('form.edit_checkout input[name="authenticity_token"]');
    const value = input.value;
    console.log(value);
})
.catch(function(error) {
    console.log(error);
});

不过,既然您使用的是await ...

const response = await axios(config);
const parser = new DOMParser;
const doc = parser.parseFromString(response, "text/html");
const input = doc.querySelector('form.edit_checkout input[name="authenticity_token"]');
const value = input.value;
console.log(value);

在 try/catch 中是更好的代码

顺便说一句,根据 HTML,querySelector 可能只是

doc.querySelector('[name="authenticity_token"]');

我在选择器中尽可能多地放入“自我文档”

【讨论】:

    猜你喜欢
    • 2021-10-13
    • 2017-12-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-09-24
    • 2021-08-02
    • 2014-08-26
    相关资源
    最近更新 更多