如何将服务连接到Cloud Foundry应用程序?

时间:2020-11-02 16:34:01

标签: javascript html node.js ibm-cloud ibm-watson

我是IBM Cloud的新手,我正在尝试构建一个应用程序,我可以在其中编写文本,按一个按钮,然后由服务色调分析器分析该文本并返回JSON,以便可以显示它。

我已经创建了该服务的实例,并使用该服务上的“连接”选项卡将其连接到我的应用程序(工具链)。 enter image description here

我的应用程序的app.js文件中也包含以下代码:

const ToneAnalyzerV3 = require('ibm-watson/tone-analyzer/v3');
const { IamAuthenticator } = require('ibm-watson/auth');

const toneAnalyzer = new ToneAnalyzerV3({
  version: '2019-10-10',
  authenticator: new IamAuthenticator({
    apikey: [API key found in service credentials],
  }),
  url: [API url found in service credentials],
});

app.get('/', function(req, res) {
  res.render('index');
});

app.post('/api/tone', async function(req, res, next) {
  try {
    const { result } = await toneAnalyzer.tone(req.body);
    res.json(result);
  } catch (error) {
    next(error);
  }
});

问题是当我在javascript上进行以下调用时:

$.post( "/api/tone", {text: textInput}, function(data){
        console.log(data);
    });

我收到错误消息:500(内部服务器错误)。

有人知道我在做什么错吗?

1 个答案:

答案 0 :(得分:1)

问题是您要发送req.body进行音调分析。如果您查看API文档-https://cloud.ibm.com/apidocs/tone-analyzer?code=node#tone-您会发现您只需要发送

const toneParams = {
  toneInput: { 'text': text },
  contentType: 'application/json',
};

我非常怀疑req.body有一个toneInput字段,如果确实有contentType,则可能未将其设置为允许值之一。