【问题标题】:My post api doesnt get executed , where as my get apis work fine. Trying to fire the api using postman, it keeps on sending the request我的 post api 没有被执行,我的 get api 在哪里工作正常。尝试使用邮递员触发 api,它继续发送请求
【发布时间】:2020-05-19 06:49:33
【问题描述】:

我在 nodejs 中使用 exrepss 框架。 服务器端代码:

这是我的服务器端代码:

router.post('/signup', function (req, res, next){
      console.log("here i am " + request.body)

      User.findOne({ $or: [{ 'local.email': req.body.email }] }, function(err, user) {
          if (err) {
               res.json(err);
          }
          if (user) {
              if (user.local.email == req.body.email) {
                 res.json({msg:"This email is already taken."})
              }


          } else {
              var userData = new User();          
              userData.local.email = req.body.email;
              userData.local.password = req.body.password;
              userData.save()
                  .then (res.json)              
                  .catch(err => {
                      console.log(err);
                      res.status(400).json({msg:"unable to save to database"});
                  })

          }
        })
      }); 

在从 Postman 触发此 api 时,我将其作为 json 格式的正文传递。

{
    "email": "qweeeee",
    "password": "1233"
}

遗漏的信息:

我也在我的 app.js 中使用会话来 ..

app.use(session({
  resave : true , 
  saveUninitialized : true,
  secret : 'keyboard cat',
  store : new MongoStore({ mongooseConnection: mongoose.connection}), //starting a new session 
  cookie : {maxAge : 180 * 60 * 1000}
}
));

.. 我相信这与 post api 没有被调用有关。如果我删除此代码,我的 GET API 也不起作用。

我的 app.js 文件如下所示。

...

var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var bodyParser = require('body-parser');
var expressHbs = require('express-handlebars');
var csurf = require ('csurf');
var cors = require('cors');
var indexRouter = require('./routes/index');

var mongoose = require ('mongoose');
var session = require('express-session')
var passport = require('passport');
var flash = require('connect-flash');
var MongoStore= require('connect-mongo')(session);
const https = require('https');

require('./config/passport');

var app = express();

app.use(cors());
app.use(express.json());
app.use(bodyParser.json());
app.use('/css', express.static(__dirname + '/node_modules/bootstrap/dist/css'));


mongoose.connect("mongodb://localhost:27017/shopping-cart", {
  useNewUrlParser: true
});
app.use(logger('dev'));

app.use(session({
  resave : true , 
  saveUninitialized : true,
  secret : 'keyboard cat',
  store : new MongoStore({ mongooseConnection: mongoose.connection}), //starting a new session 
  cookie : {maxAge : 180 * 60 * 1000}
}
)); 
app.use('/', indexRouter);

...

【问题讨论】:

  • 确保您的req.body 不为空或未定义。
  • 你使用的是 mongodb 还是 mongoose?
  • 日志中有"here i am" 文本吗?另外,我注意到.then (re.json) 还需要一个字母,否则我想它会是未定义的。
  • @gujci 我已经更正了代码中的错字。但问题仍然存在。我也没有在日志中看到“我在这里”。
  • 好的,所以整个函数都没有被调用。您能否发布将此路由器添加到中间件链的代码?

标签: node.js api express postman


【解决方案1】:

确保您正在解析请求正文。像这样的

const bodyParser = require("body-parser");
app.use(bodyParser.json());

router.post('/signup', function (req, res, next){
// access req.body here
});

【讨论】:

  • 我的 app.js 文件中已经有了这段代码。我不认为这是问题。
【解决方案2】:

?‍?您可以使用以下代码:?

router.post('/signup', function (req, res, next){

  // make sure this is not undefined
  console.log(req.body);

  User.findOne({ $or: [{ 'local.email': req.body.email }] }).then(user => {  
    if(user) {
      return res.json({msg:"This email is already taken."});
    }
    var userData = new User(req.body);
    userData.save().then(result => {
      // make sure the 
      console.log(result);
      res.send(200).json(result);
    }).catch(err => {
        console.log(err);
        res.status(400).json({msg:"unable to save to database"});
    })
  }).catch(ex => {
    console.log(ex.message);
    res.status(500).send(ex);
  })
}); 

?确保您的 req.body 不是 undefined

?‍? 如果您的req.bodyundefined,那么您可以在app.jsserver.js 中使用下面的代码。

app.use(express.json());
app.use(express.urlencoded({ extended: true }));

希望对你有帮助?。

【讨论】:

  • api 代码的第一行是 console.log ,但它不会在控制台上写任何东西。这让我觉得该控件没有进入代码本身。
  • 可能是因为你没有调用路由。因为如果你调用它,那么你肯定会看到console.log
  • 我已经在 app.js 中配置了路由器。此外,我的 GET api 存在于按预期执行的同一文件中
  • 也许你应该尝试简单的路线。在您的signup 路由的第一行,请添加res.status(200).send("Something")。让我们尝试一下,它是否有效,您就会知道,这条路线有什么问题。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-05-04
  • 1970-01-01
  • 2019-08-11
  • 2021-03-12
  • 1970-01-01
  • 2020-07-23
  • 1970-01-01
相关资源
最近更新 更多