如何在Node.js中使用Python的请求,HTTPBASICAUTH和JSON?
我在Python中制作了一些代码,使用Spotify的API并根据艺术家的输入找到图像。但是,我需要将代码添加到网站中,并且我不想处理烧瓶和异步编程。
import requests
from requests.auth import HTTPBasicAuth
import os
client_id = os.getenv("CLIENT_ID")
client_secret = os.getenv("CLIENT_SECRET")
url = 'https://accounts.spotify.com/api/token'
data = {'grant_type': 'client_credentials'}
auth=HTTPBasicAuth(client_id, client_secret)
response = requests.post(url, data=data, auth=auth)
access_token = response.json()['access_token']
artist_info = requests.get('https://api.spotify.com/v1/search/',
headers={ 'authorization': "Bearer " + access_token},
params={ 'q': input('artist: '), 'type': 'artist' })
html = artist_info.json()
html = html['artists']
html = html['items']
html = html[0]['images'][0]['url']#this is a list in a dict, twice
print(html) #this gives an image url
我的主要困惑是如何在JavaScript中导入请求和HTTPBASICAUTH,以及如何在Node.js中使用JSON。谢谢你!
I have made some code in python, to use spotify's api and find images based on an input of an artist. However, I need to add the code into a website, and I do not wish to have to deal with Flask and asynchronous programming.
import requests
from requests.auth import HTTPBasicAuth
import os
client_id = os.getenv("CLIENT_ID")
client_secret = os.getenv("CLIENT_SECRET")
url = 'https://accounts.spotify.com/api/token'
data = {'grant_type': 'client_credentials'}
auth=HTTPBasicAuth(client_id, client_secret)
response = requests.post(url, data=data, auth=auth)
access_token = response.json()['access_token']
artist_info = requests.get('https://api.spotify.com/v1/search/',
headers={ 'authorization': "Bearer " + access_token},
params={ 'q': input('artist: '), 'type': 'artist' })
html = artist_info.json()
html = html['artists']
html = html['items']
html = html[0]['images'][0]['url']#this is a list in a dict, twice
print(html) #this gives an image url
My main confusion is how to import requests and httpBasicAuth in Javascript, as well as how to use JSON in node.js. Thank you!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您的代码与任何一个无关。您不需要网络服务器/框架,只有HTTP客户端。您也不需要异步方法,尽管它们可能会帮助HTTP请求。
您不会。 JavaScript使用 fetch api 它自己的
httpagent
。注意:
fetch()
is 异步编程但是,您也可以只安装
spotify.js
(另外,async,基于Promise,Promise基于Promise),JSON不是HTML,而JSON对象是第一类对象在JavaScript中,实际上分析任何搜索结果将大多相同。
Your code has nothing to do with either. You dont need a web-server/framework, only an HTTP client. You also don't need async methods, although they might help with the HTTP requests.
You wouldn't. Javascript uses Fetch API for making web requests, and Node has its own
HttpAgent
. Note:fetch()
is asynchronous programmingHowever, you could also just install
spotify.js
(also, async, Promise-based)Regarding your variable names, JSON is not html, and JSON objects are first-class objects in Javascript, so actually parsing any search results would be mostly the same.