NodeJS to Postman Результат - PullRequest
       3

NodeJS to Postman Результат

0 голосов
/ 19 декабря 2018

Добрый день, как я могу вычислить публичную функцию для маршрутизации и проверить ее на Почтальоне?вот мои коды

router.post('/post_regular_hours/:employee_id/',function(request,response,next){
    var id = request.params.employee_id;
    var time_in = request.params.time_in;
    var time_out = request.params.time_out;
    // const timein = request.params.time_in;
    // const timeout = request.params.time_out;
    knexDb.select('*')
            .from('employee_attendance')
            .where('employee_id',id)
            .then(function(result){

                res.send(compute_normal_hours(response,result,diff))


            })
});

function compute_normal_hours(res,result,diff){

    let time_in = moment(time_in);
    let time_out = moment(time_out);


    let diff = time_out.diff(time_in, 'hours');



    return diff;

}

Я хочу, чтобы в результате Diff был опубликован на Почтальоне. Вот App.js моих кодов.Как я могу вызвать данные из запроса MySQL в функцию и вернуть вычисленные данные на пост маршрутизатора, или вы, ребята, можете дать правильную терминологию для этого.

var express = require('express');
var mysql= require('mysql');
var employee = require('./routes/employee');
var time_record = require('./routes/time_record');
var admin_employee = require('./routes/admin_employee');
var tar = require('./routes/tar');
var Joi = require('joi');

var app = express();



app.get('/hello',function(req,res){
  var name = "World";
  var schema = {
      name: Joi.string().alphanum().min(3).max(30).required()
  };
  var result = Joi.validate({ name : req.query.name }, schema);
  if(result.error === null)
  {
     if(req.query.name && req.query.name != '')
    {
      name = req.query.name;
    }
    res.json({
      "message" : "Hello "+name + "!"
    });
  }
  else
  {
    res.json({
      "message" : "Error"
    });
  }

}); 


//Database connection
app.use(function(req, res, next){
    global.connection = mysql.createConnection({
        host     : 'locahost',
        user     : 'dbm_project',
      password : 'dbm1234',
        database : 'dbm_db'
    });
    connection.connect();
    next();
});

app.use('/', employee);
app.use('/employee', time_record);
app.use('/admin', admin_employee);
app.use('/tar', tar);

// catch 404 and forward to error handler
app.use(function(req, res, next) {
  var err = new Error('Not Found');
  err.status = 404;
  next(err);
});


// error handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});

app.listen(8000,function(){
  console.log("App started on port 8000!");
});

module.exports = app;

Вот App.js моих кодов.Как я могу вызвать данные из запроса mysql в функцию и вернуть вычисленные данные на роутер po

1 Ответ

0 голосов
/ 19 декабря 2018

Есть несколько проблем с вашим кодом.Пожалуйста, смотрите объяснения в соответствующих фрагментах кода.

router.post('/post_regular_hours/:employee_id/',function(request,response,next){

    // If you're receiving a post request
    // you'll probably want to check the body for these parameters.
    let id = request.params.employee_id; // make sure the param names are matching with what you post.
    // This one is special because you are passing it through the url directly
    let time_in = request.body.time_in;
    let time_out = request.body.time_out;        

    knexDb.select('*')
            .from('employee_attendance')
            .where('employee_id',id)
            .then(function(result){

                // you are not sending time_in and time_out here - but difference. but difference is not calculated.
                // changed the function signature a bit - you weren't using the result at all? leaving this callback here because I'm sure you want to map the used time to some user?
                return response.send(compute_normal_hours(time_in, time_out))
            });
});

// this function was (and still might be) incorrect.
// You were passing res and result which neither of them you were using.
// You also had time_in and time_out which were going to be undefined in the function scope. Now that we are passing them in it should be ok. Updated it so you don't have the params you don't need.

function compute_normal_hours(time_in, time_out){
    // What was diff - if it's the time difference name things correctly
    // You had a diff parameter passed in (which you didn't compute), a diff function called below and another variable declaration called diff.
    // you were not passing time_in or time_out parameters.
    // you have moment here - are you using a library?
    let time_in = moment(time_in);
    let time_out = moment(time_out);

    let diff = time_out.diff(time_in, 'hours');

    return `Computed result is: ${diff}`;    
}

Важное редактирование

Пожалуйста, найдите все вхождения res.render (response.render) и замените их начто-то вроде res.send - res.render ищет движок шаблонов

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...