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

如何点击前端按钮调用后端say.stop()?Express新增端点实现

实现步骤

1. 后端Express新增停止语音的API端点

确保你的Express项目已完成基础配置,按以下步骤添加端点:

第一步:处理跨域(前后端端口不同时)

如果前端和后端运行在不同端口,先安装并配置CORS:

npm install cors

在Express入口文件中引入并启用:

const express = require('express');
const cors = require('cors');
const app = express();

// 允许跨域请求(生产环境建议指定具体域名)
app.use(cors());
// 解析JSON请求体
app.use(express.json());

第二步:添加停止语音的POST端点

假设你的say实例是全局可访问的TTS服务单例,添加如下路由:

// 导入你的say模块,替换为实际路径
const say = require('./path-to-your-say-module');

// 新增停止语音的API
app.post('/api/stop-speech', (req, res) => {
  try {
    say.stop();
    res.status(200).json({ message: '语音已停止' });
  } catch (err) {
    res.status(500).json({ error: '停止语音失败', details: err.message });
  }
});

// 启动服务器(示例端口3001)
app.listen(3001, () => {
  console.log('后端服务运行在 http://localhost:3001');
});

关键注意点:如果say是每个请求动态创建的实例,需要用全局变量存储当前活跃的语音实例,避免找不到对应实例:

// 全局存储当前运行的语音实例
let activeSpeechInstance = null;

// 示例:启动语音的路由
app.post('/api/start-speech', (req, res) => {
  // 创建新的语音实例
  activeSpeechInstance = createYourSpeechInstance(req.text);
  activeSpeechInstance.start();
  res.json({ message: '语音已启动' });
});

// 停止语音的路由
app.post('/api/stop-speech', (req, res) => {
  if (!activeSpeechInstance) {
    return res.status(400).json({ error: '没有正在运行的语音' });
  }
  try {
    activeSpeechInstance.stop();
    activeSpeechInstance = null; // 清空实例
    res.status(200).json({ message: '语音已停止' });
  } catch (err) {
    res.status(500).json({ error: '停止语音失败', details: err.message });
  }
});

2. 修改前端按钮的点击逻辑

将按钮注释的onClick替换为发送HTTP请求的处理函数,提供两种实现方式:

方式一:使用原生fetch

<button onClick={handleStopSpeech} className='stopspeech'>
  Stop speaking
</button>

// 定义点击处理函数
const handleStopSpeech = async () => {
  try {
    const response = await fetch('http://localhost:3001/api/stop-speech', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
    });
    const result = await response.json();
    console.log(result.message);
  } catch (err) {
    console.error('停止请求失败:', err);
  }
};

方式二:使用Axios

先安装Axios:

npm install axios

然后实现点击逻辑:

import axios from 'axios';

<button onClick={handleStopSpeech} className='stopspeech'>
  Stop speaking
</button>

const handleStopSpeech = async () => {
  try {
    const response = await axios.post('http://localhost:3001/api/stop-speech');
    console.log(response.data.message);
  } catch (err) {
    console.error('停止请求失败:', err.response?.data?.error || err.message);
  }
};

内容的提问来源于stack exchange,提问作者Abhishek

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 01:21:04