【问题标题】:Unexpected token " in JSON at position 0位置 0 处的 JSON 中的意外标记“
【发布时间】:2021-12-21 00:48:46
【问题描述】:

我的目标是在数组中添加 ObjectId 在我的后端,我在此代码上声明架构:

   tchStudents: [{
      type: Schema.Types.ObjectId, 
      ref: "Student"
   }]

然后我添加一个 ObjectId 以插入到 ObjectID 数组中: 我的后端很好

  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'
         });
     
         } else {

        let query = { tchID: req.params.tchID }
        let assignedStudentObjID = {$push:{tchStudents: req.body.tchStudents }}

        Teacher.updateOne(query, assignedStudentObjID ,() => {
          try{
             return res.status(200).send({
                success: true,
                msg: 'Student ID has been assigned' 
             });
          } catch(err) {
            console.log(err);
            return res.status(404).send({
              success: false,
              error: 'Teacher ID not found'
           })
         }
       }) 
   }

 } catch (err) {
  console.log(err)
 }

 })

但我的前端无法正常工作 err: BAD REQUEST(400) Unexpected token " in JSON at position 0

import React, {useState} from 'react'

import axios from 'axios'

import { URL } from '../../utils/utils'

import { Modal, Button } from 'react-materialize';

import ListTchStudents from '../lists/ListTchStudents';

const trigger = 
    <Button 
       style={{marginLeft:'2rem'}} 
       tooltip="Add More..."
       tooltipOptions={{
          position: 'top'
       }}
      className="btn-small red darken-4">
      <i className="material-icons center ">add_box</i>
    </Button>;

const MdlAddStudents =({teacher}) => {

const [data, setData] = useState('');

const { tchStudents} = data;

const {
  tchID, 
} = teacher; // IF WE RENDER THIS IT TURNS INTO OBJECT

const assignedStudent = () => {
  
  // BUT WE SENT IT TO THE DATABASE CONVERT TO JSON.STRINGIFY to make ObjectId
  const requestOpt = {
     method: 'PUT',
     headers: { 'Content-Type': 'application/json'},
     body: JSON.stringify(data)
  }

  axios.put(`${URL}teachers/assignAddStudents/${tchID}`, data,requestOpt)
     .then(res => {
        setData(res.data.data)
     })

}

return (
  <Modal header="Add Students" trigger={trigger}>
     Please ADD and REMOVE Student ID No. for {tchID}

     <div>
     <ul
        style={{marginBottom:'2rem'}}
        className="collection">
        {
           Object.values(teacher.tchStudents).map(tchStudent => {
              return(
                 <ListTchStudents 
                    tchStudent={tchStudent}
                 />
              ); 
           })
        }
     </ul>

     <div className="row">
         <div className="col s6 offset-s3"></div>
            <div className="input-field">
               <label 
                  htmlFor="" 
                  className="active black-text"
                  style={{fontSize:'1.3rem'}}>
                  Add Students here:
               </label>
               <input 
                  type="text"
                  name="tchStudents"
                  value={(tchStudents)}
                  className="validate"
                  onChange={(e) => setData(e.target.value)}
               />
            </div>
         </div>
     </div>
    
     {/* BUT WE SENT IT TO THE DATABASE CONVERT TO JSON.STRINGIFY to send ObjectId to the database 
     */}
     <div className="row">
        <div className="col s2 offset-s3" ></div>
              <Button 
                 onClick={assignedStudent}
                 tooltip="Add Students"
                 tooltipOptions={{
                    position: 'right'
                 }}
                 className="btn green darken-3">
                 <i className="material-icons ">add_circle</i>
              </Button>
        </div> 
        <p>There are {Object.values(teacher.tchStudents).length} student/s 
        assigned</p>

 </Modal>
 )
}

// MdlAddStudents.propTypes = {
//    assignedStudents: PropTypes.func.isRequired,
// }


export default MdlAddStudents;
// export default connect(null, (assignedStudents))(MdlAddStudents);

感谢您的帮助

【问题讨论】:

  • 如果data 是一个对象,为什么要将它初始化为一个空字符串?此外,您的 requestOpt 对象是完全没有必要的
  • 至于错误本身:您正在尝试解析 JSON,但您没有接收 JSON。
  • 但我想将 ObjectID 保存到数据库中

标签: node.js reactjs mongoose axios


【解决方案1】:

问题源于您试图将 tchStudents 状态属性包装在名为 data 的对象中。

我的建议是保持简单

// it's just a string
const [tchStudents, setTchStudents] = useState("")

const assignedStudent = () => {
  // create your request payload
  const data = { tchStudents }

  // no config object required
  axios.put(`${URL}teachers/assignAddStudents/${tchID}`, data)
    .then(res => {
      // not sure what you want to do here exactly but
      // `res.data` should look like
      // { success: true, msg: 'Student ID has been assigned' }
      setTchStudents("") // clear the input ¯\_(ツ)_/¯
    })
}

唯一的其他变化是在您的 &lt;input&gt; 中使用新的 setter 名称...

<input 
  type="text"
  name="tchStudents"
  value={tchStudents}
  className="validate"
  onChange={(e) => setTchStudents(e.target.value)}
/>

【讨论】:

  • 由useCallback 是react 模块的一部分吗?
  • @Borgs 我删除了useCallback(),不是必需的
  • 成功了 非常感谢我为我的申请工作创建了自己的投资组合,在哪里可以远程申请工作?
猜你喜欢
  • 2021-10-22
  • 1970-01-01
  • 2021-02-20
  • 2020-07-02
  • 2018-11-25
  • 2016-09-21
  • 2021-05-06
相关资源
最近更新 更多