You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

基于Node.js开发集成IBM Watson Conversation的网页

嘿,我来帮你搞定这个问题!你已经搞定了和IBM Watson对话的Node.js逻辑,现在就差把它和前端HTML串起来了,我给你一步步拆解,保证你能快速跑起来:

第一步:改造Node.js代码,提供前端可调用的API接口

前端没法直接调用Watson的服务,得靠你的Node.js后端当中间层。咱们用Express搭个简单的服务器,开个POST接口来处理用户消息,调用Watson后返回回复。

首先装依赖:

npm install express body-parser

然后修改你的Node.js代码(假设叫server.js):

const express = require('express');
const bodyParser = require('body-parser');
const AssistantV2 = require('ibm-watson/assistant/v2');
const { IamAuthenticator } = require('ibm-watson/auth');

const app = express();
app.use(bodyParser.json());
app.use(express.static('public')); // 托管前端静态文件(HTML、图片都放这)

// 初始化Watson Assistant(替换成你的配置)
const assistant = new AssistantV2({
  version: '2021-06-14',
  authenticator: new IamAuthenticator({
    apikey: '你的Watson API密钥',
  }),
  serviceUrl: '你的Watson服务URL',
});

// 创建会话(V2版本需要会话ID,V1版本可以跳过这部分)
let sessionId;
assistant.createSession({ assistantId: '你的助手ID' })
  .then(res => {
    sessionId = res.result.session_id;
    console.log('Watson会话已创建');
  })
  .catch(err => console.error('会话创建失败:', err));

// 处理用户消息的API接口
app.post('/api/message', (req, res) => {
  const userInput = req.body.message;

  assistant.message({
    assistantId: '你的助手ID',
    sessionId: sessionId,
    input: {
      message_type: 'text',
      text: userInput
    }
  })
  .then(response => {
    // 提取Watson的回复文本(根据你的Watson配置可能需要调整路径)
    const botReply = response.result.output.generic[0].text;
    res.json({ reply: botReply });
  })
  .catch(err => {
    console.error('Watson调用出错:', err);
    res.status(500).json({ error: '抱歉,我暂时没法回复你' });
  });
});

// 启动服务器
const PORT = 3000;
app.listen(PORT, () => {
  console.log(`服务器跑起来啦!访问 http://localhost:${PORT}`);
});
第二步:创建前端聊天界面

在项目根目录新建一个public文件夹,所有前端文件都放这里。在里面创建index.html,写一个带聊天窗口和图片的页面:

<!DOCTYPE html>
<html>
<head>
  <title>Watson聊天机器人</title>
  <style>
    /* 整体聊天容器 */
    .chat-container {
      width: 450px;
      margin: 30px auto;
      border: 1px solid #ddd;
      border-radius: 10px;
      overflow: hidden;
      box-shadow: 0 2px 10px rgba(0,0,0,0.1);
    }
    /* 顶部图片区域 */
    .bot-header {
      padding: 15px;
      background-color: #f5f5f5;
      display: flex;
      justify-content: center;
      gap: 20px;
    }
    .bot-header img {
      width: 70px;
      height: 70px;
      border-radius: 50%;
      object-fit: cover;
      border: 2px solid #007bff;
    }
    /* 聊天消息区域 */
    .chat-messages {
      height: 450px;
      padding: 15px;
      overflow-y: auto;
      background-color: #fafafa;
    }
    /* 消息样式 */
    .message {
      margin-bottom: 12px;
      padding: 8px 15px;
      border-radius: 20px;
      max-width: 75%;
      word-wrap: break-word;
    }
    .user-message {
      background-color: #007bff;
      color: white;
      margin-left: auto;
    }
    .bot-message {
      background-color: white;
      color: #333;
      margin-right: auto;
      border: 1px solid #eee;
    }
    /* 输入区域 */
    .input-area {
      display: flex;
      padding: 10px;
      background-color: white;
      gap: 10px;
    }
    #user-input {
      flex: 1;
      padding: 10px 15px;
      border: 1px solid #ddd;
      border-radius: 25px;
      outline: none;
    }
    #send-btn {
      padding: 10px 20px;
      border: none;
      border-radius: 25px;
      background-color: #007bff;
      color: white;
      cursor: pointer;
    }
    #send-btn:hover {
      background-color: #0056b3;
    }
  </style>
</head>
<body>
  <div class="chat-container">
    <!-- 顶部机器人图片 -->
    <div class="bot-header">
      <img src="robot-avatar1.jpg" alt="机器人头像1">
      <img src="robot-avatar2.jpg" alt="机器人头像2">
    </div>
    <!-- 聊天消息展示区 -->
    <div class="chat-messages" id="chat-messages">
      <div class="message bot-message">你好呀!我是Watson助手,有什么我能帮你的吗?</div>
    </div>
    <!-- 用户输入区 -->
    <div class="input-area">
      <input type="text" id="user-input" placeholder="输入你的消息...">
      <button id="send-btn">发送</button>
    </div>
  </div>

  <script>
    const chatMessages = document.getElementById('chat-messages');
    const userInput = document.getElementById('user-input');
    const sendBtn = document.getElementById('send-btn');

    // 发送消息到后端
    function sendMessage(message) {
      // 先把用户消息加到界面上
      addMessage(message, 'user');

      // 调用后端API
      fetch('/api/message', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ message: message })
      })
      .then(res => res.json())
      .then(data => {
        // 把机器人回复加到界面上
        addMessage(data.reply, 'bot');
      })
      .catch(err => {
        console.error('发送失败:', err);
        addMessage('抱歉,我现在有点故障...', 'bot');
      });

      // 清空输入框
      userInput.value = '';
    }

    // 往聊天窗口添加消息
    function addMessage(text, sender) {
      const messageDiv = document.createElement('div');
      messageDiv.className = `message ${sender}-message`;
      messageDiv.textContent = text;
      chatMessages.appendChild(messageDiv);
      // 自动滚动到最新消息
      chatMessages.scrollTop = chatMessages.scrollHeight;
    }

    // 绑定发送按钮点击事件
    sendBtn.addEventListener('click', () => {
      const message = userInput.value.trim();
      if (message) sendMessage(message);
    });

    // 绑定回车键发送
    userInput.addEventListener('keypress', (e) => {
      if (e.key === 'Enter') {
        const message = userInput.value.trim();
        if (message) sendMessage(message);
      }
    });
  </script>
</body>
</html>
第三步:准备图片并测试
  1. 把你要展示的机器人图片(比如robot-avatar1.jpg、robot-avatar2.jpg)放到public文件夹里,和index.html同级。
  2. 把Node.js代码里的Watson配置(API密钥、服务URL、助手ID)替换成你自己的。
  3. 启动服务器:node server.js。
  4. 打开浏览器访问http://localhost:3000,就能看到带图片的聊天窗口了,发送消息就能和Watson对话啦!

如果你的Watson用的是V1版本,只需要调整后端调用Watson的代码逻辑,核心的前端和后端交互方式是一样的。

内容的提问来源于stack exchange,提问作者S.Gilliland

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 04:14:16