Axios请求接口报错Unexpected token " in JSON at position 0求助
问题原因排查
1. 前端state结构错误
你当前把data的初始值设为空字符串'',但实际需要传递的是包含tchStudents字段的对象,且input的onChange直接把输入的纯字符串赋值给data,导致data最终就是普通字符串而非结构化对象。后续解构const { tchStudents} = data也拿不到有效值,因为字符串无法解构出tchStudents字段。
2. axios请求参数格式错误
axios的put方法第二个参数本身就是请求体,你先传了纯字符串类型的data,第三个参数又传入了包含body: JSON.stringify(data)的配置,等于重复传递请求体。且你传递的data是纯字符串,不符合后端要求的JSON结构,后端解析时就会抛出Unexpected token " in JSON at position 0的格式错误。
3. 请求配置冗余错误
axios本身会自动为对象类型的请求体添加Content-Type: application/json请求头,无需手动配置。且你写的requestOpt里的body字段是fetch API的写法,axios不识别该字段,属于无效配置。
修复步骤
前端代码修改:
- 修正state的初始值和更新逻辑
将原有代码:
const [data, setData] = useState(''); const { tchStudents} = data;
修改为:
// 初始值设为对象,包含对应字段 const [data, setData] = useState({tchStudents: ''}); const { tchStudents } = data;
再修改input的onChange逻辑,只更新对象内的tchStudents字段:
onChange={(e) => setData({...data, tchStudents: e.target.value})}
- 修正axios请求逻辑,删除多余配置
将原有assignedStudent方法修改为:
const assignedStudent = () => { // axios自动将对象转为JSON格式,自动添加正确的请求头 axios.put(`${URL}teachers/assignAddStudents/${tchID}`, data) .then(res => { // 接口返回值中无data字段,可按需调整逻辑,比如清空输入框:setData({tchStudents: ''}) }) .catch(err => console.log(err)) }
后端代码优化(可选,不影响当前报错,仅提升规范度)
你当前updateOne回调内的try catch无效,无法捕获异步操作的错误,建议改为async await写法:
router.put('/assignAddStudents/:tchID', async (req,res) => { try { const searchTch = await Teacher.findOne({ tchID: req.params.tchID }) if(!searchTch){ return res.status(404).send({ success: false, error: 'Teacher ID not found' }); } await Teacher.updateOne({ tchID: req.params.tchID }, {$push:{tchStudents: req.body.tchStudents }}) return res.status(200).send({ success: true, msg: 'Student ID has been assigned' }); } catch (err) { console.log(err) return res.status(500).send({ success: false, error: '服务器错误' }) } })
内容的提问来源于stack exchange,提问作者Borgs
相关产品推荐
相关产品推荐

