我正在尝试创建一个节点js服务器但是它不起作用。它说每次低于错误我在节点js中进行crud操作,用mongoose和express dependecies
由Command node server.js运行服务器时出错
C:\用户\拉希尔\桌面\ codenode \ node_modules \路径对正则表达式\ index.js:34
.concat(严格?'':'/?')
^ TypeError:path.concat不是函数
在pathtoRegexp(C:\ Users \ Rahil \ Desktop \ codenode \ node_modules \ path-to-regexp)
\ index.js:34:6)
在新层(C:\ Users \ Rahil \ Desktop \ codenode \ node_modules \ express \ lib \ route
r \ layer.js:21:17)
在Function.proto.route(C:\ Users \ Rahil \ Desktop \ codenode \ node_modules \ expres
小号\ LIB \路由器\ index.js:364:15)
在Function.app。(匿名函数)[as put](C:\ Users \ Rahil \ Desktop \ codeno
德\ node_modules \表现\ LIB \ application.js中:405:30)
在对象。 (C:\用户\拉希尔\桌面\ codenode \ server.js:86:9)
在Module._compile(module.js:409:26)
at Object.Module._extensions..js(module.js:416:10)
在Module.load(module.js:343:32)
在Function.Module._load(module.js:300:12)
在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');
};
答案 0 :(得分:0)
您的代码中有两个错误:
app.put( function(req, res) {
/*...*/
}
应该是:
router.put( function(req, res) {
/*.....*/
} )
这同样适用于app.delete
我认为你应该寻找更好的教程。