首页 文章

node js server未开始显示错误

提问于
浏览
0

我正在尝试创建一个节点js服务器但它's not working. It says every time below error i'在节点js中使用mongoose和express dependecies进行crud操作
通过命令节点server.js运行服务器时出错C:\ Users \ Rahil \ Desktop \ codenode \ node_modules \ path-to-regexp \ index.js:34 .concat(strict?'' : ' /?')^ TypeError:path . concat不是新层的pathtoRegexp(C:\ Users \ Rahil \ Desktop \ codenode \ node_modules \ path-to-regexp \ index.js:34:6)中的函数(C:\ Users \ Rahil \ Desktop \ codenode \在function.proto.route(C:\ Users \ Rahil \ Desktop \ codenode \ node_modules \ expres s \ lib \ router \ index.js:364:node_modules \ express \ lib \ route r \ layer.js:21:17) 15)在Object的Function.app . (匿名函数)[as put](C:\ Users \ Rahil \ Desktop \ codeno de \ node_modules \ express \ lib \ application.js:405:30) . (C:\ Users \ Rahil \ Desktop \ codenode \ server.js:86:9)在Module._compile(module.js:409:26)处于Object.Module._extensions..js(module.js:416:10) )在Function.Module.runMain(module.js:441:10)的Function.Module._load(module.js:300:12)的Module.load(module.js:343:32)

----------
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');
  };

1 回答

  • 0

    你的代码有两个错误:

    app.put( function(req, res) {
         /*...*/ 
    }
    

    应该:

    router.put( function(req, res) {
        /*.....*/
    } )
    

    这同样适用于 app.delete .
    我认为你应该寻找更好的教程 .

相关问题