该错误是由于在没有catch块的情况下抛出异步函数而产生的

问题描述

当我尝试将数据插入db而不引用表中的其他集合时,它可以正常工作。但是当我通过将收藏链接到其他收藏来使用ref时,它说:

[SyntaxError: JSON Parse error: Unexpected identifier "Orders"]并在服务器命令提示符下,显示如下错误。我不明白这是什么错误。我的裁判有任何问题,还是由于未处理的承诺被拒?

请帮助我。预先感谢。

错误

[nodemon] restarting due to changes...
[nodemon] starting `node index index.js`
server running at port3000
connected to mongodb server !!!
(node:18536) DeprecationWarning: collection.ensureIndex is deprecated. Use createIndexes instead.
{ Order_ID: 100,User_ID: 1 }
(node:18536) UnhandledPromiseRejectionWarning: Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
    at ServerResponse.setHeader (_http_outgoing.js:518:11)
    at ServerResponse.header (R:\ReactNativeProjects\AuthServer\node_modules\express\lib\response.js:771:10)
    at ServerResponse.send (R:\ReactNativeProjects\AuthServer\node_modules\express\lib\response.js:170:12)
    at R:\ReactNativeProjects\AuthServer\routes\authRoutes.js:76:9
    at processticksAndRejections (internal/process/task_queues.js:97:5)
(node:18536) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block,or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection,use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)
(node:18536) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future,promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

我的模式:

const Users = new Schema({
    User_ID:{ type:Number,required:true,unique:true },userName: { type: String,required:true},dob: Date,emailID:String,mobileNo: { type:Number,required:true },status:{ type:String,required:true }
});

const Orders = new Schema({
    Order_ID: {type:Number,unique:true},User_ID:[{type:Schema.Types.ObjectId,ref: 'Users'}],});

路由器:

router.post('/Orders',async(req,res) => {

    console.log(req.body);
    const {Order_ID,User_ID} = req.body;
    try {
        const order = new Orders({Order_ID,User_ID});
        await order.save();
        res.send("successful transaction !!");
    }catch(err) {
        res.status(422).send(err.message);
    }
});

我将数据插入db的代码

fetch("http://10.0.2.2:3000/Orders ",{
       method:"POST",headers : {
          "Content-Type" : 'application/json'
       },body: JSON.stringify({ 
          "Order_ID":100,"User_ID":1
       })
})
.then(res=>res.json())
.then(data => {
     console.log(data);
}).
catch((error) => {
   console.log(error);
});


解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)