以下是我用於從本地計算機查詢API進行測試的代碼。
var watson = require('watson-developer-cloud');
var personality_insights = watson.personality_insights({
username: '<username>',
password: '<password>',
version: 'v2'
});
var express = require('express');
var app = express();
var http = require('http').Server(app);
var server_port = 8080
var server_ip_address = '127.0.0.1'
var bodyParser = require('body-parser')
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: true
}));
app.use('/', express.static(__dirname + '/public'));
app.get("/", function(req, res){
res.sendFile(__dirname + '/public/index.html');
});
app.post("/post", function(req, res){
getInsights(req.body.text,res);
});
function getInsights(text,res) {
var params = {};
params.text = text;
personality_insights.profile(params, function(error, response) {
if (error)
console.log('error:', error);
else {
res.send(JSON.stringify(response));
}
});
}
http.listen(server_port,server_ip_address, function(){
console.log("Listening on " + server_ip_address + ", server_port " + server_port)
});
我在公用文件夾一個簡單的index.html對我來說,在文本輸入和發送過來的NodeJS
<!doctype html>
<html>
<head>
<title>Status</title>
<style>
</style>
</head>
<body>
<div style="margin:10px"><textarea style="width:100%;height:500px;" id="text"></textarea></div>
<div>Words: <span id="count">0</span> <button onClick="onSubmit()">Submit</button></div>
<br/><br/>
<div id="response">
</div>
</body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<script src="Countable.js"></script>
<script>
var word_counter = 0;
var area = document.getElementById('text')
Countable.live(area, function (counter) {
$("#count").html(counter.words);
//console.log(counter);
word_counter = counter.words;
});
function onSubmit() {
if (word_counter < 100) {
$("#response").html("Please provide at least 100 words");
return;
}
var text = $("#text").val();
$.ajax({
type: "POST",
url: '/post',
data: {text:text.trim()},
dataType: "json",
success: function(data) {
$("#response").html(data);
}
})
}
</script>
</html>
希望幫助
你可以添加你在做什麼看到這裏錯了嗎?我需要更多的輸出,如控制檯錯誤等 – broguinn
沒有什麼wrog它在我的命令行工作,並希望在我的locahost網站上使用它。我想整合在我的網頁上。我正在尋找一個例子,或者如果某人可以爲我提供步驟,這將是偉大的 – user3026665