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

ReactJS:输入框优化管理与REST响应多数据项展示技术问询

React前端调用带参数的REST API并展示结果

针对你的需求,我分两部分给你具体的实现方案:

1. 如何让用户输入db_name和sql_query变量?

最直观的方式是通过React表单收集用户输入,考虑到SQL语句通常较长,给sql_query使用多行文本域会更友好。这里是一个基础的表单实现示例:

import { useState } from 'react';

function ApiQueryForm() {
  // 管理输入状态
  const [dbName, setDbName] = useState('');
  const [sqlQuery, setSqlQuery] = useState('');

  const handleSubmit = (e) => {
    e.preventDefault();
    // 后续在这里添加API调用逻辑
    console.log('用户提交的参数:', { dbName, sqlQuery });
  };

  return (
    <form onSubmit={handleSubmit} style={{ margin: '20px' }}>
      <div style={{ marginBottom: '10px' }}>
        <label>数据库名称(db_name):</label>
        <input
          type="text"
          value={dbName}
          onChange={(e) => setDbName(e.target.value)}
          placeholder="比如A123vSearch"
          required
          style={{ marginLeft: '10px', padding: '5px' }}
        />
      </div>
      <div style={{ marginBottom: '10px' }}>
        <label>SQL查询语句:</label>
        <textarea
          value={sqlQuery}
          onChange={(e) => setSqlQuery(e.target.value)}
          placeholder="比如SELECT DATE,LABEL_NUMBER,FILENAME FROM FILE_INFO_SEARCH WHERE FILENAME MATCH 'C:/Test_Software/opencv_world320.dll'"
          required
          rows={5}
          cols={80}
          style={{ marginLeft: '10px', padding: '5px' }}
        />
      </div>
      <button type="submit" style={{ padding: '8px 16px' }}>执行查询</button>
    </form>
  );
}

export default ApiQueryForm;

这个表单会实时收集用户输入的两个参数,点击提交按钮后即可触发后续的API调用流程。

2. 调用API并展示响应结果

接下来需要把表单收集到的参数拼接成合法的API地址,发起请求后将结果展示出来。这里要注意SQL语句中的特殊字符需要编码,避免URL解析错误,用encodeURIComponent处理是标准做法。

下面是完整的组件实现,包含API调用、状态管理和结果展示:

import { useState } from 'react';

function ApiQueryViewer() {
  const [dbName, setDbName] = useState('');
  const [sqlQuery, setSqlQuery] = useState('');
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState('');
  const [apiResponse, setApiResponse] = useState(null);

  const handleSubmit = async (e) => {
    e.preventDefault();
    setLoading(true);
    setError('');
    setApiResponse(null);

    try {
      // 编码SQL查询语句,处理空格、引号等特殊字符
      const encodedSql = encodeURIComponent(sqlQuery);
      // 拼接完整的API地址
      const apiUrl = `http://127.0.0.1:5002/sqlquery/${dbName}/${encodedSql}`;
      
      const response = await fetch(apiUrl);
      
      if (!response.ok) {
        throw new Error(`请求失败: ${response.status} ${response.statusText}`);
      }

      const data = await response.json();
      setApiResponse(data);
    } catch (err) {
      setError(err.message);
    } finally {
      setLoading(false);
    }
  };

  return (
    <div style={{ padding: '20px' }}>
      <form onSubmit={handleSubmit}>
        <div style={{ marginBottom: '10px' }}>
          <label>数据库名称(db_name):</label>
          <input
            type="text"
            value={dbName}
            onChange={(e) => setDbName(e.target.value)}
            placeholder="比如A123vSearch"
            required
            style={{ marginLeft: '10px', padding: '5px' }}
          />
        </div>
        <div style={{ marginBottom: '10px' }}>
          <label>SQL查询语句:</label>
          <textarea
            value={sqlQuery}
            onChange={(e) => setSqlQuery(e.target.value)}
            placeholder="比如SELECT DATE,LABEL_NUMBER,FILENAME FROM FILE_INFO_SEARCH WHERE FILENAME MATCH 'C:/Test_Software/opencv_world320.dll'"
            required
            rows={5}
            cols={80}
            style={{ marginLeft: '10px', padding: '5px' }}
          />
        </div>
        <button 
          type="submit" 
          disabled={loading}
          style={{ padding: '8px 16px', cursor: loading ? 'not-allowed' : 'pointer' }}
        >
          {loading ? '查询中...' : '执行查询'}
        </button>
      </form>

      {/* 错误提示区域 */}
      {error && <div style={{ color: 'red', marginTop: '20px' }}>错误: {error}</div>}

      {/* 加载状态提示 */}
      {loading && <div style={{ marginTop: '20px' }}>正在加载数据,请稍候...</div>}

      {/* 查询结果展示区域 */}
      {apiResponse && (
        <div style={{ marginTop: '20px' }}>
          <h3>查询结果:</h3>
          {Array.isArray(apiResponse) ? (
            <table border="1" style={{ borderCollapse: 'collapse', marginTop: '10px' }}>
              <thead>
                <tr>
                  {/* 动态生成表头 */}
                  {Object.keys(apiResponse[0]).map((key) => (
                    <th key={key} style={{ padding: '8px' }}>{key}</th>
                  ))}
                </tr>
              </thead>
              <tbody>
                {/* 动态生成数据行 */}
                {apiResponse.map((item, index) => (
                  <tr key={index}>
                    {Object.values(item).map((value, idx) => (
                      <td key={idx} style={{ padding: '8px' }}>{value}</td>
                    ))}
                  </tr>
                ))}
              </tbody>
            </table>
          ) : (
            <pre style={{ backgroundColor: '#f5f5f5', padding: '10px', borderRadius: '4px' }}>
              {JSON.stringify(apiResponse, null, 2)}
            </pre>
          )}
        </div>
      )}
    </div>
  );
}

export default ApiQueryViewer;

额外的注意事项:

  • 跨域问题:如果你的React应用和API不在同一域名/端口下,会遇到CORS错误,需要在后端API配置跨域允许(比如Flask中使用flask-cors插件)。
  • SQL注入风险:如果前端面向普通用户,后端必须做严格的SQL注入防护,不能直接将用户输入的SQL语句传入数据库执行。
  • 输入验证:可以给表单添加输入格式校验(比如检查db_name是否符合命名规则、SQL语句是否包含危险关键词),提升安全性和用户体验。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 09:13:55