samedi 11 juin 2016

node js server does not start showing error

I am trying to make a node js server But it's not working. It says every time below error i'm doing crud operation in node js with mongoose and express dependecies
Error while running server by Command node server.js C:UsersRahilDesktopcodenodenode_modulespath-to-regexpindex.js:34 .concat(strict ? '' : '/?') ^TypeError: path.concat is not a function at pathtoRegexp (C:UsersRahilDesktopcodenodenode_modulespath-to-regexp index.js:34:6) at new Layer (C:UsersRahilDesktopcodenodenode_modulesexpresslibroute rlayer.js:21:17) at Function.proto.route (C:UsersRahilDesktopcodenodenode_modulesexpres slibrouterindex.js:364:15) at Function.app.(anonymous function) [as put] (C:UsersRahilDesktopcodeno denode_modulesexpresslibapplication.js:405:30) at Object. (C:UsersRahilDesktopcodenodeserver.js:86:9) at Module._compile (module.js:409:26) at Object.Module._extensions..js (module.js:416:10) at Module.load (module.js:343:32) at Function.Module._load (module.js:300:12) at Function.Module.runMain (module.js:441:10)

----------
Code Server.js
    // BASE SETUP
   // 
===================================================================

// call the packages we need
var express    = require('express');        // call express
var app        = express();                 // define our app using express
var bodyParser = require('body-parser');

var mongoose   = require('mongoose');
mongoose.connect('mongodb://127.0.0.1:27017/company'); // connect to our databas


var Company     = require('./app/models/companies');

// configure app to use bodyParser()
// this will let us get the data from a POST
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());

var port = process.env.PORT || 8080;        // set our port

// ROUTES FOR OUR API
// =============================================================================
var router = express.Router();              // get an instance of the express Router
// middleware to use for all requests
router.use(function(req, res, next) {
    // do logging
    console.log('Something is happening.');
    next(); // make sure we go to the next routes and don't stop here
});
// test route to make sure everything is working (accessed at GET http://localhost:8080/company)

router.get('/', function(req, res) {
    res.json({ message: 'hooray! welcome !' });   
});

// more routes for our company will happen here
// on routes that end in /company
// ----------------------------------------------------
router.route('/addcompany')

// create a company (accessed at POST http://localhost:8080/company/addcompany)
.post(function(req, res) {

    var company = new Company();      // create a new instance of the Company model
    company.company_name = req.body.company_name; 
    company.reg_no = req.body.reg_no;
    company.address = req.body.address;
    company.contact_name = req.body.contact_name;
    company.phone_no = req.body.phone_no;
     // set the addcompany name (comes from the request)

    // save the company and check for errors
    company.save(function(err) {
        if (err)
            res.send(err);

        res.json({ message: 'Company created!' });
    });

});
app.get('/addcompany', function(req, res) {
    Company.find(function(err, companies) {
        if (err)
            res.send(err);

        res.json(companies);
    });
});

router.route('/:company_id')

// get the company with that id (accessed at GET http://localhost:8080/company/addcompany/:company_id)
.get(function(req, res) {
    Company.findById(req.params.company_id, function(err, company) {
        if (err)
            res.send(err);
        res.json(company);
    });
});




// update the company with this id (accessed at PUT http://localhost:8080/company/addcompany/:company_id)
app.put(function(req, res) {

    // use our company model to find the company we want
    Company.findById(req.params.company_id, function(err, company) {

        if (err)
            res.send(err);

        company.company_name = req.body.company_name; 
        company.reg_no = req.body.reg_no;
        company.address = req.body.address;
        company.contact_name = req.body.contact_name;
        company.phone_no = req.body.phone_no;  // update the company info

        // save the company
        company.save(function(err) {
            if (err)
                res.send(err);

            res.json({ message: 'Company updated!' });
        });

    });
});

// delete the company with this id (accessed at DELETE http://localhost:8080/company/addcompany/:company_id)
app.delete(function(req, res) {
    Company.remove({
        _id: req.params.company_id
    }, function(err, company) {
        if (err)
            res.send(err);

        res.json({ message: 'Successfully deleted' });
    });
});
// REGISTER OUR ROUTES -------------------------------
// all of our routes will be prefixed with /company


app.use('/company', router);

// START THE SERVER
// =============================================================================
app.listen(port);
console.log('Magic happens on port ' + port);



END OF SERVER.JS

----------
var mongoose     = require('mongoose');
var Schema       = mongoose.Schema;

var CompanySchema   = new Schema({
    company_name: String,
    reg_no: String,
    address: String,
    contact_name: String,
    phone_no: String
});

module.exports = mongoose.model('Companies', CompanySchema);
END OF COMPANIES.JS
----------
package.json 
{
  "name": "node-api",
  "main": "server.js",
  "dependencies": {
    "body-parser": "~1.0.1",
    "express": "~4.0.0",
    "mongoose": "~3.6.13"
  }
 }




PLEASE FIND THE SOLUTION >>>>> THANKING YOU


Here is index,js file 
   /**
      * Expose `pathtoRegexp`.
      */

  module.exports = pathtoRegexp;

  /**
  * Normalize the given path string,
  * returning a regular expression.
  *
  * An empty array should be passed,
  * which will contain the placeholder
  * key names. For example "/user/:id" will
  * then contain ["id"].
  *
  * @param  {String|RegExp|Array} path
  * @param  {Array} keys
  * @param  {Object} options
  * @return {RegExp}
  * @api private
  */

  function pathtoRegexp(path, keys, options) {
  options = options || {};
  var sensitive = options.sensitive;
  var strict = options.strict;
  var end = options.end !== false;
  keys = keys || [];

  if (path instanceof RegExp) return path;
  if (path instanceof Array) path = '(' + path.join('|') + ')';

  path = path
    .concat(strict ? '' : '/?')
    .replace(//(/g, '/(?:')
    .replace(/([/.])/g, '\$1')
    .replace(/(\/)?(\.)?:(w+)((.*?))?(*)?(?)?/g, function (match, slash, format, key, capture, star, optional) {
      slash = slash || '';
      format = format || '';
      capture = capture || '([^/' + format + ']+?)';
      optional = optional || '';

      keys.push({ name: key, optional: !!optional });

      return ''
        + (optional ? '' : slash)
        + '(?:'
        + format + (optional ? slash : '') + capture
        + (star ? '((?:[\/' + format + '].+?)?)' : '')
        + ')'
        + optional;
    })
    .replace(/*/g, '(.*)');

  return new RegExp('^' + path + (end ? '$' : '(?=/|$)'), sensitive ? '' : 'i');
  };

Aucun commentaire:

Enregistrer un commentaire