[英]What is the equivalent for pythons requests.post method in JavaScript?
我嘗試在 Javascript 中連接到 googles Perspective API。 我已經嘗試了很多我研究過的東西,但沒有任何效果。 但是當我在 Python 中嘗試它時,它非常容易......所以基本上我需要在 JavaScript 中使用與以下簡單 Python 代碼等效的代碼。 它必須在瀏覽器插件中工作。
import json
import requests
api_key = '<MYAPIKEY>'
url = ('https://commentanalyzer.googleapis.com/v1alpha1/comments:analyze'+'?key='+api_key)
data_dict = {
'comment': {'text': 'text to be checked'},
'languages': ['en'],
'requestedAttributes': {'TOXICITY': {}}
}
response = requests.post(url=url, data=json.dumps(data_dict))
response_dict = json.loads(response.content)
我不是 JavaScript 專家,我真的需要幫助來解決這個問題,我希望有人能幫助我。
您必須使用 fetch (或 axios),例如:
fetch(url, {
method: "POST",
headers: {
Accept: "application/json",
"Content-Type": "application/json"
}
body: JSON.stringify(data),
}).then(res => res.json())
.then(data => console.log(data))
.catch(err => console.log(err));
您可以使用fetch api 。
const api_key = '<MYAPIKEY>';
const url = ('https://commentanalyzer.googleapis.com/v1alpha1/comments:analyze'+'?key='+api_key);
const data_dict = {
'comment': {'text': 'text to be checked'},
'languages': ['en'],
'requestedAttributes': {'TOXICITY': {}}
};
fetch(url, {
method: 'POST',
body: JSON.stringify(data_dict)
})
.then(response => response.json())
.then(data => {
// do whatever with the data from the response
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.