uni-app后端收到前端数据为null

在实现注册功能时,前端使用uni.request向http://localhost:8080/register发送POST请求。初始时,后端收到的数据为null。问题出在缺少正确的请求头,添加content-type:application/x-www-form-urlencoded后,后端能正确接收数据。同时,后端需将控制器注解由@Controller改为@RestController,以避免程序解析为页面报错。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

问题与解决措施:

实现注册功能,插入一条新数据,包括用户的用户名、密码和手机号。使用uni.request请求传数据到后端接口。接口名称为http://localhost:8080/register,是POST请求。但是一开始后端收到的数据为null,查看前端数据是没有问题的,数据类型都是String类型。经过一番查阅之后发现需要加上请求头才能使后端正确接收到数据。

前端:

uni.request({
    url: 'http://localhost:8080/register',
    method: 'POST',
    data: {
        name: this.username,
        password: this.password,
        phone: this.phone
    },
    header: {
    	'content-type': 'application/x-www-form-urlencoded'
    },
    success: (res) => {
        uni.showToast({
            title: '注册成功',
            icon: 'success'
        })
        uni.navigateBack()
    },
    fail: () => {
        uni.showToast({
            title: '注册失败',
            icon: 'error'
        })
    }
})

重要:

header: {
    'content-type': 'application/x-www-form-urlencoded'
}

后端:

@PostMapping("/register")
public void register(String name, String password, String phone) {
    userManageService.addNewUser(name, password, phone);
}

注意:

后端我并没有加@ResponseBody注解,但是为了不让程序解析为页面报错,必须将控制器的注解从@Controller改为@RestController,这一点值得注意。

<think>嗯,用户现在问的是如何在uni-app开发小程序时实现前端录音并上传到后端前端代码。之前他们问过后端接收和保存文件的问题,现在可能是在同一个项目里需要前端部分的实现。我需要先回顾一下之前给的后端处理步骤,确保前端代码和后端能够对接。 首先,用户的需求是录音并上传,所以前端部分需要包括录音功能的实现和文件上传的逻辑。uni-app支持多平台,但小程序有自己的API,比如微信小程序的getRecorderManager,可能需要针对不同平台做适配,但用户可能主要关心微信小程序的情况,所以应该以这个为例。 接下来,我要考虑uni-app中如何调用录音功能。需要检查权限,因为小程序录音需要用户授权,这部分代码需要处理授权请求。然后,开始录音、停止录音的事件处理,以及获取临时文件路径。 然后,上传部分需要用到uni.uploadFile方法,注意小程序中这个API是特有的,和HTML5的FormData不同。需要设置url、filePath、name等参数,还要处理上传的成功和失败回调。 另外,用户可能还需要实时显示录音状态,比如显示录音时长,所以需要一个计时器来更新界面上的时间显示。同时,录音文件的格式和大小限制也是需要注意的,可能需要提醒用户在后端做相应的验证。 可能用户没有提到的点包括:录音前的权限检查失败处理,不同平台之间的兼容性问题,以及上传过程中的加载状态提示。这些都需要在代码中考虑进去,比如添加权限拒绝时的提示,使用uni.showLoading来提升用户体验。 最后,示例代码的结构应该清晰,包括模板、脚本和样式的部分,方便用户直接复制使用。同时,注意事项部分要强调测试步骤、后端接口的匹配以及安全措施,确保用户在实际部署时不会遗漏关键配置。</think>以下是使用uni-app实现小程序录音并上传的前端代码实现方案,分为核心代码实现和关键逻辑说明: --- ### 一、录音功能实现 ```html <template> <view class="container"> <button @tap="startRecord" :disabled="isRecording">开始录音</button> <button @tap="stopRecord" :disabled="!isRecording">停止录音</button> <text>录音时长:{{ duration }}秒</text> </view> </template> <script> export default { data() { return { isRecording: false, duration: 0, recorderManager: null, tempFilePath: '' // 录音临时文件路径 } }, mounted() { this.initRecorder() }, methods: { // 初始化录音管理器 initRecorder() { this.recorderManager = uni.getRecorderManager() this.recorderManager.onStart(() => { this.isRecording = true this.startTimer() }) this.recorderManager.onStop((res) => { this.tempFilePath = res.tempFilePath this.isRecording = false this.stopTimer() this.uploadAudio() // 自动触发上传 }) }, // 开始录音 async startRecord() { try { const auth = await uni.authorize({ scope: 'scope.record' }) this.recorderManager.start({ format: 'mp3', // 支持格式:aac/mp3 duration: 60 // 最大录音时长60秒 }) } catch (err) { uni.showToast({ title: '录音权限未开启', icon: 'none' }) } }, // 停止录音 stopRecord() { this.recorderManager.stop() }, // 计时器控制 startTimer() { this.timer = setInterval(() => { this.duration += 1 }, 1000) }, stopTimer() { clearInterval(this.timer) this.duration = 0 } } } </script> ``` --- ### 二、文件上传实现 ```javascript methods: { // 上传音频文件 async uploadAudio() { if (!this.tempFilePath) { uni.showToast({ title: '请先完成录音', icon: 'none' }) return } uni.showLoading({ title: '上传中...' }) try { const res = await uni.uploadFile({ url: 'https://your-api-domain.com/upload', filePath: this.tempFilePath, name: 'audio_file', formData: { user_id: '123', // 附加参数 timestamp: Date.now() } }) if (res.statusCode === 200) { const data = JSON.parse(res.data) uni.showToast({ title: '上传成功' }) console.log('文件地址:', data.url) } else { throw new Error('上传失败') } } catch (err) { uni.showToast({ title: '上传失败', icon: 'none' }) } finally { uni.hideLoading() } } } ``` --- ### 三、关键配置说明 1. **录音参数配置**: ```javascript recorderManager.start({ format: 'mp3', // 输出格式 sampleRate: 44100, // 采样率 numberOfChannels: 1 // 单声道 }) ``` 2. **上传安全策略**: ```javascript // 添加请求头 header: { 'Authorization': 'Bearer ' + token, 'X-File-Size': file.size // 后端校验文件大小 } ``` 3. **多平台适配**: ```javascript // #ifdef MP-WEIXIN // 微信小程序特定代码 // #endif ``` --- ### 四、注意事项 1. **真机调试**: - 小程序需开启录音权限 - 配置合法域名(`uni.request`白名单) 2. **文件限制**: ```javascript // 校验文件大小(示例限制10MB) if (file.size > 10 * 1024 * 1024) { uni.showToast({ title: '文件超过10MB限制' }) return } ``` 3. **性能优化**: ```javascript // 压缩音频(需使用插件如:pcm-to-mp3) const compressedPath = await this.compressAudio(this.tempFilePath) ``` --- ### 五、完整流程图 ```mermaid sequenceDiagram participant 用户 participant 小程序 participant 服务器 用户->>小程序: 点击开始录音 小程序->>服务器: 请求录音权限 服务器-->>小程序: 返回授权状态 小程序->>小程序: 启动录音并计时 用户->>小程序: 点击停止录音 小程序->>小程序: 生成临时文件 小程序->>服务器: 上传音频文件 服务器-->>小程序: 返回上传结果 小程序->>用户: 显示上传状态 ``` --- **推荐扩展功能**: 1. 实时波形显示(使用`<canvas>`绘制) 2. 语音识别集成(结合WebSocket实时转文字) 3. 上传进度显示(通过`onProgressUpdate`事件) ```javascript // 监听上传进度 uni.uploadFile({ // ...其他参数 success: (res) => { /* ... */ }, fail: (err) => { /* ... */ }, complete: () => { /* ... */ }, // 进度更新 progress: (res) => { console.log('进度:', res.progress) } }) ```
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值