首页 > 解决方案 > Node.js,如何从一些我必须在其中输入用户名和密码的 url 获取 JSON 元素?

问题描述

我使用这个功能:

var getJSON = function(url, callback) {
    var xhr = new XMLHttpRequest();
    xhr.open('GET', url, true);
    xhr.responseType = 'json';
    xhr.onload = function() {
        var status = xhr.status;
        if (status === 200) {
            callback(null, xhr.response);
        } else {
            callback(status, xhr.response);
        }
    };
    xhr.send();
};

函数调用:

 getJSON('http://localhost:8080/job/'+jobName+'/lastBuild/api/json?tree=timestamp',
        function(err, data) {
            if (err !== null) {
               console.log('Something went wrong: ' + err);
            } else {
                console.log('Your query count: ' + data.query.count);
            }
    });

我收到 403 错误,表示需要凭据

标签: node.jsjsonurlhttp-status-code-403

解决方案


您可以使用 axios 库来完成。

var axios = require("axios");

var url = "your-url";

async function getData(url) {
  try {
    var response = await axios.get(url);
    var data = response.data;
    console.log(data);
  } catch (error) {
    console.log(error);
  }
};

getData(url);

您需要使用以下命令安装 axios 库:

npm install axios --save

推荐阅读