原生JS请求API

GET方式前端- 多个参数

javascript 复制代码
// 场景:查询数据 GET方式
async function getData() {
    const params = {
        sceneId: 'order_123',
        userId: 'user_456',
        type: 'normal'
    };


    // 方式2:使用URLSearchParams(推荐)
    const queryString = new URLSearchParams(params).toString();
    const url2 = `/api/data?${queryString}`;

    const response = await fetch(url2);
    const data = await response.json();
    return data;
}

GET方式后端:

c# 复制代码
[HttpGet("data")]
public IActionResult GetData([FromQuery] SceneQueryParams query)
{
    // 直接通过对象访问
    return Ok(new { 
        query.SceneId, 
        query.UserId, 
        query.Type, 
        message = "GET请求成功" 
    });
}

POST方式-前端:

javascript 复制代码
// 场景:提交复杂对象
async function createOrder() {
    const postData = {
        sceneId: 'order_123',
        userInfo: {
            name: '张三',
            phone: '13800000000'
        },
        items: [
            { id: 1, price: 99.9 },
            { id: 2, price: 199.9 }
        ]
    };

    const response = await fetch('/api/order', {
        method: 'POST',                 // 指定POST方法
        headers: {
            'Content-Type': 'application/json'  // 声明发送JSON
        },
        body: JSON.stringify(postData)  // 序列化为JSON字符串
    });

    if (!response.ok) {
        throw new Error(`请求失败: ${response.status}`);
    }

    const result = await response.json();
    console.log('创建成功:', result);
    return result;
}

POST方式-后端:

c# 复制代码
[HttpPost("order")]
public IActionResult CreateOrder([FromBody] OrderDto dto)
{
    // dto已经自动反序列化
    return Ok(new { 
        success = true, 
        message = "订单创建成功",
        sceneCode = $"{dto.SceneId}_{Random.Shared.Next(0, 1000000).ToString("D6)}"
    });
}

再举例-修改数据:POST

后端控制器
c# 复制代码
// Controllers/SceneController.cs
[ApiController]
[Route("api/scene")]
public class SceneController : ControllerBase
{
    [HttpPost("update-code")]
    public IActionResult UpdateSceneCode([FromBody] string sceneId)
    {
        // 参数验证
        if (string.IsNullOrWhiteSpace(sceneId))
            return BadRequest(new { success = false, message = "sceneId不能为空" });

        try
        {
            // 生成场景编码
            string sceneCode = $"{sceneId}_{Random.Shared.Next(0, 1000000).ToString("D6)}";
            
            // **模拟数据库更新**(实际项目中替换为真实DB操作)
            Console.WriteLine($"[模拟数据库更新] sceneId={sceneId}, sceneCode={sceneCode}");
            
            return Ok(new { 
                success = true, 
                sceneCode, 
                message = "生成成功" 
            });
        }
        catch (Exception ex)
        {
            // 记录错误日志(实际项目中用ILogger)
            Console.WriteLine($"[错误] {ex.Message}");
            return StatusCode(500, new { success = false, message = "服务异常" });
        }
    }
}
前端JS
javascript 复制代码
// 按钮事件:传递sceneId
async function generateAndSaveSceneCode(sceneId) {
    // 验证参数
    if (!sceneId) {
        alert('sceneId不能为空');
        return;
    }

    // 显示加载状态
    const button = document.activeElement;
    if (button) button.disabled = true;

    try {
        // POST提交单个参数
        const response = await fetch('/api/scene/update-code', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify(sceneId)  // 直接序列化字符串
        });

        if (!response.ok) {
            throw new Error(`HTTP错误: ${response.status}`);
        }

        const result = await response.json();
        
        if (result.success) {
            // 成功后打开二维码页面
            const url = `/miniprogram/checkinqrcode.html?scene=${encodeURIComponent(result.sceneCode)}`;
            window.open(url, '_blank', 'noopener,noreferrer');
            
            console.log('场景编码生成成功:', result.sceneCode);
        } else {
            alert('生成失败: ' + result.message);
        }

    } catch (error) {
        console.error('操作失败:', error);
        alert('生成失败: ' + error.message);
    } finally {
        // 恢复按钮状态
        if (button) button.disabled = false;
    }
}
相关推荐
林恒smileZAZ1 分钟前
Electron 的西天取经
前端·javascript·electron
傻乐u兔2 分钟前
C语言初阶————结构体
c语言·开发语言
weixin_445054722 分钟前
力扣热题52
开发语言·python
逑之5 分钟前
C语言笔记2:C语言数据类型和变量
c语言·开发语言·笔记
何中应6 分钟前
@Autowrited和@Resource注解的区别及使用场景
java·开发语言·spring boot·后端·spring
源代码•宸7 分钟前
Golang语法进阶(Context)
开发语言·后端·算法·golang·context·withvalue·withcancel
一条咸鱼_SaltyFish7 分钟前
[Day16] Bug 排查记录:若依框架二次开发中的经验与教训 contract-security-ruoyi
java·开发语言·经验分享·微服务·架构·bug·开源软件
源代码•宸8 分钟前
Golang语法进阶(Sync、Select)
开发语言·经验分享·后端·算法·golang·select·pool
一勺菠萝丶10 分钟前
Java 对接 PLC 实战:西门子 PLC 与永宏 PLC 通讯方式全面对比
java·开发语言·python
吴声子夜歌10 分钟前
Java数据结构与算法——数论问题
java·开发语言