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

如何将HTML表单数据提交到REST API对接gatewayapi实现短信发送

实现方案

重要提示:绝对不要将GatewayAPI的授权凭证直接写在前端代码中,会被恶意用户窃取后滥用发送短信,产生额外费用,所有第三方API调用必须在后端服务中处理

1. 前端页面代码(包含手机号表单)

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>短信发送</title>
</head>
<body>
    <form id="smsForm">
        <input type="tel" id="phone" name="phone" placeholder="请输入手机号" required>
        <input type="submit" value="提交获取短信">
    </form>

    <script>
        const form = document.getElementById('smsForm')
        form.addEventListener('submit', async (e) => {
            e.preventDefault()
            const phone = document.getElementById('phone').value.trim()
            // 可自行补充手机号格式校验逻辑
            try {
                const res = await fetch('/api/send-sms', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({ phone: phone })
                })
                if (res.ok) {
                    alert('短信发送成功,请注意查收')
                    form.reset()
                } else {
                    alert('发送失败,请稍后重试')
                }
            } catch (err) {
                console.error('请求异常', err)
                alert('网络异常,请检查后重试')
            }
        })
    </script>
</body>
</html>

2. 后端中转接口示例(以Node.js + Express为例)

替换代码中的YOUR_GATEWAY_API_BASIC_TOKEN为你自己的实际授权凭证即可使用,也可自行适配其他语言的后端框架:

const express = require('express')
const axios = require('axios')
const app = express()

// 解析JSON请求体
app.use(express.json())

// 前端调用的短信发送接口
app.post('/api/send-sms', async (req, res) => {
    const { phone } = req.body
    // 后端二次校验手机号格式,避免恶意请求
    if (!phone || !/^1[3-9]\d{9}$/.test(phone)) {
        return res.status(400).json({ msg: '手机号格式错误' })
    }
    try {
        // 调用GatewayAPI接口
        await axios.post('https://gatewayapi.com/rest/mtsms', {
            message: "你要发送的短信内容",
            recipients: [
                // 国内手机号需要拼接86国家码,可根据实际需求调整
                { msisdn: Number('86' + phone) }
            ]
        }, {
            headers: {
                'Authorization': 'Basic YOUR_GATEWAY_API_BASIC_TOKEN',
                'Accept': 'application/json',
                'Content-Type': 'application/json'
            }
        })
        res.status(200).json({ msg: '发送成功' })
    } catch (err) {
        console.error('调用短信接口失败', err)
        res.status(500).json({ msg: '发送失败' })
    }
})

app.listen(3000, () => {
    console.log('服务启动在3000端口')
})

其他注意事项

  • 建议添加发送频率限制,避免同一手机号短时间内多次请求
  • 正式上线前建议加图形验证码或者行为验证,防止接口被恶意刷取

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 19:15:03