简体   繁体   中英

How do you fetch JSON from Google's Cloud Natural Language API based on existing text using client-side JS?

Does anyone know how to retrieve data from Google's Cloud Natural Language (NL) API using client-side javascript? What is incorrect with the code block below - likely line 29?

I've been looking at a lot of documentation today to figure out how to perform sentiment analysis using Google's Cloud NL API. Many of them have not been very clear.

This tutorial helped me understand how Google's Cloud NL API works to a large degree.

I still have a few gaps.

This is the block of code I derived after looking at a few docs.

One area I think that may be a potential issue, line 29. I've never fetched using two arguments.

1  sentiApiKey = ***API KEY***
2  sentiEndPoint = ***Google's Cloud Natural Language endpoint***
3  //dictData is existing JSON data

5  function searchSenti(dictData) {
6     const sentiParams = {
7         key: sentiApiKey,
8     }

10    const sentiApiKeyString = formatQueryParams(sentiParams)
11    const sentiUrl = sentiAnEndPoint + "?" + sentiApiKeyString;

13    const def = dictData[0].shortdef[0]
14    const dict = {
15        language: 'en-us',
16        type: 'PLAIN_TEXT',
17        content: def
18    };

20    const nlApiData = {
21        document: dict,
22        encodingType: 'UTF8'
23    };

25    const nlCallOptions = {
26        method: 'post',
27        contentType: 'application/json',
28        payload: JSON.stringify(nlApiData)
29    }

31    fetch(sentiUrl, nlCallOptions)
32    .then(response => {
33        if (response.ok) {
34            return response.json();
35        }
36        throw new Error(response.statusText);
37    })
38    .then(sentiData => parseSenti(sentiData))
39    .catch(err => {
40        $("#error-message").removeClass("hidden");
41        $("#js-error-message").text(`Something went wrong with the 
          Sentiment API: ${err.message}`);
43    });
44 }

46 function parseSenti(sentiData) {
47    const data = JSON.parse(sentiData);
48    const sentiment = 0.0;

50    if (data && data.documentSentiment && data.documentSentiment.score){
51       sentiment = data.documentSentiment.score;
52    }

54    console.log(sentiment);
55 }

A few days ago, I learned that there is no way to use Google's Cloud Natural Language API using client-side JS.

Here's some documentation that will help you use client-side JS for sentiment analysis: http://www.gtlambert.com/blog/sentiment-analysis-sentimoodjs https://github.com/thinkroth/Sentimental

Cheers.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM