使用node.js的Watson api

使用node.js的Watson api,node.js,ibm-cloud,ibm-watson,Node.js,Ibm Cloud,Ibm Watson,我正在尝试使用node.js代码来使用watson api,它位于ios应用程序中的ibm cloud bluemix中。有谁能告诉我这段代码在做什么,并为我们提供一个如何从我们的应用程序使用watson服务的答案吗 var express = require('express'); var https = require('https'); var url = require('url'); // setup middleware var app = express(); app.use(

我正在尝试使用node.js代码来使用watson api,它位于ios应用程序中的ibm cloud bluemix中。有谁能告诉我这段代码在做什么,并为我们提供一个如何从我们的应用程序使用watson服务的答案吗

var express = require('express');
var https = require('https');
var url = require('url');

// setup middleware

var app = express();
app.use(express.errorHandler());
app.use(express.urlencoded()); // to support URL-encoded bodies
app.use(app.router);

app.use(express.static(__dirname + '/public')); //setup static public directory
app.set('view engine', 'jade');
app.set('views', __dirname + '/views'); //optional since express defaults to CWD/views

// There are many useful environment variables available in process.env.
// VCAP_APPLICATION contains useful information about a deployed application.

var appInfo = JSON.parse(process.env.VCAP_APPLICATION || "{}");
// TODO: Get application information and use it in your app.

// defaults for dev outside bluemix

var service_url = '<service_url>';
var service_username = '<service_username>';
var service_password = '<service_password>';

// VCAP_SERVICES contains all the credentials of services bound to
// this application. For details of its content, please refer to
// the document or sample of each service.

if (process.env.VCAP_SERVICES) {
  console.log('Parsing VCAP_SERVICES');
  var services = JSON.parse(process.env.VCAP_SERVICES);

//service name, check the VCAP_SERVICES in bluemix to get the name of the services you have

var service_name = 'question_and_answer';

  if (services[service_name]) {
    var svc = services[service_name][0].credentials;
    service_url = svc.url;
    service_username = svc.username;
    service_password = svc.password;
  } else {
    console.log('The service '+service_name+' is not in the VCAP_SERVICES, did you forget to bind it?');
  }

} else {
  console.log('No VCAP_SERVICES found in ENV, using defaults for local development');
}

console.log('service_url = ' + service_url);
console.log('service_username = ' + service_username);
console.log('service_password = ' + new Array(service_password.length).join("X"));

var auth = "Basic " + new Buffer(service_username + ":" +    service_password).toString("base64");

// render index page

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

// Handle the form POST containing the question to ask Watson and reply with the answer

app.post('/', function(req, res){

// Select healthcare as endpoint 

var parts = url.parse(service_url +'/v1/question/healthcare');
// create the request options to POST our question to Watson

var options = { host: parts.hostname,
    port: parts.port,
    path: parts.pathname,
    method: 'POST',
    headers: {
      'Content-Type'  :'application/json',
      'Accept':'application/json',
      'X-synctimeout' : '30',
      'Authorization' :  auth }
  };

// Create a request to POST to Watson

var watson_req = https.request(options, function(result) {
    result.setEncoding('utf-8');
    var response_string = '';

    result.on('data', function(chunk) {
      response_string += chunk;
    });

    result.on('end', function() {
      var answers_pipeline = JSON.parse(response_string),
          answers = answers_pipeline[0];
      return res.render('index',{'questionText': req.body.questionText, 'answers': answers})
   })

  });

  watson_req.on('error', function(e) {
    return res.render('index', {'error': e.message})
  });

// create the question to Watson

var questionData = {
    'question': {
      'evidenceRequest': { 
        'items': 5 // the number of anwers
      },
      'questionText': req.body.questionText // the question
    }
  };

// Set the POST body and send to Watson

 watson_req.write(JSON.stringify(questionData));
 watson_req.end();

});

// The IP address of the Cloud Foundry DEA (Droplet Execution Agent) that hosts this application:

var host = (process.env.VCAP_APP_HOST || 'localhost');
// The port on the DEA for communication with the application:

var port = (process.env.VCAP_APP_PORT || 3000);
// Start server

app.listen(port, host);
var express=require('express');
var https=require('https');
var url=require('url');
//安装中间件
var-app=express();
app.use(express.errorHandler());
app.use(express.urlencoded());//支持URL编码的实体
应用程序使用(应用程序路由器);
app.use(express.static(uu dirname+/public))//设置静态公共目录
应用程序集(“查看引擎”、“翡翠”);
app.set('views','u dirname+'/views')//可选,因为express默认为CWD/views
//process.env中有许多有用的环境变量。
//VCAP_应用程序包含有关已部署应用程序的有用信息。
var appInfo=JSON.parse(process.env.VCAP_应用程序| |“{}”);
//TODO:获取应用程序信息并在应用程序中使用。
//bluemix外部开发的默认值
var服务url='';
var服务\ u用户名=“”;
var服务_密码=“”;
//VCAP_服务包含绑定到的服务的所有凭据
//这个应用程序。有关其内容的详情,请参阅
//每项服务的文档或样本。
if(过程环境VCAP_服务){
log(“解析VCAP_服务”);
var services=JSON.parse(process.env.VCAP_服务);
//服务名称,检查bluemix中的VCAP_服务以获取您拥有的服务的名称
var服务名称='问题和答案';
if(服务[服务名称]){
var svc=services[service_name][0]。凭据;
service_url=svc.url;
服务_username=svc.username;
服务密码=svc.password;
}否则{
log('服务'+service_name+'不在VCAP_服务中,您忘记绑定了吗?');
}
}否则{
log(“在ENV中找不到VCAP_服务,使用本地开发的默认值”);
}
log('service\u url='+service\u url);
log('service\u username='+service\u username);
log('service\u password='+新数组(service\u password.length).join(“X”);
var auth=“Basic”+新缓冲区(服务\用户名+:“+服务\密码);
//呈现索引页
app.get('/',函数(req,res){
res.render(“索引”);
});
//处理包含问题的表格帖子,询问沃森并用答案回答
app.post(“/”,函数(请求,res){
//选择医疗保健作为端点
var parts=url.parse(service_url+'/v1/question/healthcare');
//创建请求选项,将我们的问题发布到Watson
var options={host:parts.hostname,
端口:parts.port,
路径:parts.pathname,
方法:“POST”,
标题:{
“内容类型”:“应用程序/json”,
“接受”:“应用程序/json”,
“X-synctimeout”:“30”,
“授权”:auth}
};
//创建向Watson发布的请求
var watson_req=https.request(选项、函数(结果){
结果:设置编码('utf-8');
var响应_字符串=“”;
result.on('data',函数(块){
响应_字符串+=块;
});
result.on('end',function(){
var answers\u pipeline=JSON.parse(响应字符串),
answers=answers_管道[0];
返回res.render('index',{'questionText':req.body.questionText,'answers':answers})
})
});
watson_请求开启('error',函数(e){
返回res.render('index',{'error':e.message})
});
//向沃森提问
变量数据={
问题:{
“证据查询”:{
“项目”:5//安瓦尔的数量
},
“questionText”:req.body.questionText//问题
}
};
//设置邮件正文并发送给Watson
watson_req.write(JSON.stringify(questionData));
沃森要求结束();
});
//承载此应用程序的Cloud Foundry DEA(水滴执行代理)的IP地址:
var host=(process.env.VCAP_APP_host | | |'localhost');
//DEA上用于与应用程序通信的端口:
变量端口=(process.env.VCAP_APP_port | 3000);
//启动服务器
应用程序侦听(端口、主机);

此代码的大部分用于节点和在BlueMix环境中执行
VCAP_SERVICES
是一个Bluemix环境变量,用于获取您感兴趣使用的给定服务的凭据。在这种情况下,
服务\u名称
设置为“问答”以访问问答平台服务

在Bluemix环境中,您应该有一个问答服务实例和一个应用程序。当应用程序绑定到问答服务时,它会创建一个服务绑定。服务绑定具有访问服务实例的应用程序凭据。在本例中,
VCAP_SERVICES
包含用于与服务实例通信和验证的绑定的URL、用户名和密码

从你的iOS应用程序中,你需要一些东西。首先,您需要一个服务绑定,现在必须在Bluemix中创建它。在Bluemix中拥有凭据后,您可以在iOS应用程序中使用这些凭据。或者你可以在Bluemix上托管一个应用程序,让它处理与Watson的通信

接下来,您需要能够调用问答服务,这是一个RESTful服务。在上面的代码中,变量
options
包含向Watson服务发布问题所需的信息。请注意,从凭据获得的
服务\u url
附加了一个额外的路径信息,以使用Watson For Healthcare域

从那里你可以创建你的问题。变量
questionData
包含上述代码中的问题。
question.questionText
属性设置为您想问Watson的问题,例如,“我应该每天服用阿司匹林吗?”

然后,您可以将问题发布到Watson,如下代码片段所示:

watson_req.write(JSON.stringify(questionData));
节点是异步的,所以
result.on('end', function() {
  var answers_pipeline = JSON.parse(response_string),
      answers = answers_pipeline[0];
  return res.render('index',{'questionText': req.body.questionText, 'answers': answers})
   })
app.get('/api/question', function(req, res){
    // Call the service with a question and get an array with the answers
    var answers = watson.question(req.query);
    // Send the answers and the question to the client in json
    res.json({answers: answers, question: req.query.question});
});
   http://my-cool-app.mybluemix.net