【问题标题】:mongodb, the second res.json errormongodb,第二个 res.json 错误
【发布时间】:2017-12-08 18:13:41
【问题描述】:

我对第二个res.json 有一些问题。我试过了:

res.json({500,message : 'xxxxxx'})

res.send({500,message : 'xxxxxx'})

但还是不行。这是我的代码:

import mongoose from 'mongoose';
import {Router} from 'express';
import Motor from '../model/motor';

export default({config,db}) =>{
  let api = Router();

  //  '/v1/motor/add'
  api.post('/add',(res,req) => {
    let newMotor = new Motor();
    newMotor.title = req.body.title;

    newMotor.save(err = {
       if(err){
          res.json({message : 'error'});
       }
       res.json({message : 'motor saved successfuly'});
     });
  });

  return api;
}

这是错误信息:

SyntaxError: C:/Users/Ali Baltschun/Desktop/motorDB/src/controller/motor.js: Unexpected token, expected , (17:6)
  15 |         res.json({message : 'error'});
  16 |       }
> 17 |       res.json({message : 'motor saved successfuly'});
     |       ^
  18 |     });
  19 |   });

【问题讨论】:

  • 我打赌第一个也失败了。它只是在错误条件之外无法到达。
  • 你犯了一些愚蠢的 sintax 错误。我建议您在尝试做某事之前先回到语言的基础知识。
  • 问题是我忘记了bodyParser
  • 您确定要err = { 而不是err => {

标签: javascript json mongodb


【解决方案1】:

res.json 期待一个有效的 json 对象,所以

res.json({500,message : 'xxxxxx'})

上面的行会失败

你也应该返回 res.json

 newMotor.save(err = {
       if(err){
          return res.json({message : 'error'});
       }
       return res.json({message : 'motor saved successfuly'});
     });
  });

接下来,如果你想发送 500 代码服务器错误,你可以这样做

res.status(500).json({message : 'error'})

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-09-08
    • 2019-09-29
    • 2014-06-04
    • 2017-06-23
    • 1970-01-01
    • 1970-01-01
    • 2018-06-26
    • 1970-01-01
    相关资源
    最近更新 更多