uniapp如何发送表单数据

在uniapp中如何发送表单数据到后端?我尝试使用uni.request提交数据,但后端接收不到参数。正确的参数格式应该是form-data还是json?需要设置特定的请求头吗?有没有完整示例代码可以参考?

2 回复

在uni-app中,使用uni.request发送表单数据。如果是普通表单,设置header'Content-Type': 'application/x-www-form-urlencoded',数据用data参数传递。如果是文件上传,用uni.uploadFile方法。


在 UniApp 中发送表单数据通常通过以下步骤实现:

  1. 准备表单数据:将数据整理为对象格式。
  2. 使用网络请求 API:主要通过 uni.request 发送数据。
  3. 设置请求参数:指定 URL、请求方法、数据体和请求头。

示例代码

// 在某个方法中(如按钮点击事件)
submitForm() {
  // 表单数据对象
  const formData = {
    username: 'exampleUser',
    password: 'examplePassword',
    email: 'user@example.com'
  };

  // 发送 POST 请求
  uni.request({
    url: 'https://example.com/api/submit', // 替换为你的接口地址
    method: 'POST',
    data: formData, // 表单数据
    header: {
      'Content-Type': 'application/json' // 根据后端要求设置,常见为 application/json 或 application/x-www-form-urlencoded
    },
    success: (res) => {
      console.log('提交成功:', res.data);
      uni.showToast({ title: '提交成功', icon: 'success' });
    },
    fail: (err) => {
      console.error('提交失败:', err);
      uni.showToast({ title: '提交失败', icon: 'none' });
    }
  });
}

关键点说明:

  • Content-Type
    • application/json:数据以 JSON 格式发送(如上例)。
    • application/x-www-form-urlencoded:数据需编码为查询字符串格式(使用 qs 库或 URLSearchParams 处理)。
  • GET 请求:若用 GET,将数据放在 data 中会自动转为 URL 查询参数。
  • 文件上传:如需上传文件,使用 uni.uploadFile,数据通过 formData 参数传递。

注意事项:

  • 确保网络权限已配置(如 manifest.json 中的合法域名)。
  • 处理跨域问题需后端配合或使用代理。
  • 实际开发中建议对数据校验和加密。

根据你的后端接口要求调整 Content-Type 和数据格式即可。

回到顶部