node.js - 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 错误,表示需要凭据
解决方案
您可以使用 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
推荐阅读
- javascript - 来自内部的角度访问功能,然后在承诺中
- angular - 如何在悬停时打开导航栏 ngbDropdown?
- docker - Windows Docker NAT 似乎完全崩溃了
- google-colaboratory - 使 colab 使用最新安装的库
- internet-explorer - Internet Explorer 中的多个 Select2 标记问题
- javascript - 访问用户集合中的数组。[Meteor + React Native]
- unity3d - Unity3D - 为什么以简单复制的方式重构我的脚本不起作用?
- javascript - 将 Array.push 作为参数传递会在 JavaScript 中引发异常
- sql - RODBC:围绕 SQL Server APPENDS 的日期时间值引用
- git - 在 VSCode 中跟踪子文件夹中的 git 更改