node.js https get request



我正试图在我的后端node.js web应用程序中发出http请求。我可以在前端web javascript文件上成功发出http请求,如下所示:

$.ajax({
url: `https://api.spotify.com/v1/artists/${artistId}/albums`,
type: 'GET',
contentType: 'application/json',
headers: {
'Authorization': 'Bearer ' + globalAccesToken,
},
data: {
offset: offset,
}
}).done(function callback(response) {

resolve(response.items)

}).fail(async function (error) {
getArtistAlbums(artistId, offset, onlyReturnTracks))
});

从下面的指南:https://nodejs.dev/learn/make-an-http-post-request-using-nodejs

我一直试图在node.js后端做出相同的请求:

//get access token
let accessToken = await spotifyAuth.getAccessToken();

//create data
const data = JSON.stringify({
offset: 0,
})
//create options data obj
const options = {
hostname: 'https://api.spotify.com',
path: '/v1/artists/1XqqyIQYMonHgllb1uysL3/albums',
//url: 'https://api.spotify.com/v1/artists/1XqqyIQYMonHgllb1uysL3/albums',
method: 'GET',
headers: {
'Authorization': 'Bearer ' + accessToken,
},
}
const req = https.request(options, res => {
console.log(`proxyiprequest() statusCode: ${res.statusCode}`)
res.on('data', d => {
process.stdout.write(d)
})
})

req.on('error', error => {
console.error('proxyiprequest() err=', error)
})

req.write(data)
req.end()

但是运行上面的请求以这个err结束:

proxyiprequest() err= { Error: getaddrinfo ENOTFOUND https://api.spotify.com https://api.spotify.com:443
at GetAddrInfoReqWrap.onlookup [as oncomplete] (dns.js:56:26)
errno: 'ENOTFOUND',
code: 'ENOTFOUND',
syscall: 'getaddrinfo',
hostname: 'https://api.spotify.com',
host: 'https://api.spotify.com',
port: 443 }

我做错了我如何设置我的url/路径设置?

节点https模块有一个单独的选项名为protocol。因此,在请求选项中,您不应该包含https://http://

你的选项变量将变成:

const options = {
hostname: 'api.spotify.com',
path: '/v1/artists/1XqqyIQYMonHgllb1uysL3/albums',
method: 'GET',
headers: {
'Authorization': 'Bearer ' + accessToken,
},
}

相关内容

  • 没有找到相关文章

最新更新