节点js服务器不会启动显示错误
我想做一个节点js服务器但它不工作。它说,下面的错误每次我做CRUD操作与猫鼬节点js和表达依赖条件
错误运行的命令节server.js C服务器同时:\用户\拉希尔\桌面\ codenode \ node_modules \路径TO- regexp \ index.js:34 .concat(strict?'':'/?') ^ TypeError:path.concat不是函数 at pathtoRegexp(C:\ Users \ Rahil \ Desktop \ codenode \ node_modules \ path (C:\ Users \ Rahil \ Desktop \ codenode \ node_modules \ express \ lib \ route r \ layer.js:21:17) at-regexp \ index.js:34:6) at Function.proto.route(C:\ Users \ Rahil \ Desktop \ codenode \ node_modules \ expres s \ lib \ router \ index.js:364:15) at Fun ction.app(匿名函数)为put]。(C:\用户\拉希尔\桌面\ codeno 德\ node_modules \表达\ lib中\的application.js:405:30) 在对象。 (C:\用户\拉希尔\桌面\ codenode \ server.js:86:9) 在Module._compile(module.js:409:26) 在Object.Module._extensions..js(module.js:416 (module.js:443:32) at Function.Module._load(module.js:300:12) at Function.Module.runMain(module.js:441:10)节点js服务器不会启动显示错误
----------
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');
};
有一个在你的代码两个错误:
app.put(function(req, res) {
/*...*/
}
应该是:
router.put(function(req, res) {
/*.....*/
})
这同样适用于app.delete
。
我认为你应该寻找一个更好的教程。
你可以请建议一些好的nodejs教程我是新的nodejs,但仍然有一个错误 –
[官方指南](http://expressjs.com/en/starter/basic-routing.html)是相当不错的。基本上,你需要学习路由,这是告诉服务器当它收到像“http://your.domain.com/user/54375634”这样的请求时要使用哪个函数。然后,服务器可能会从数据库中获取数据,呈现数据并返回响应。 @RahilAnsari – Zen
粘贴你的index.js文件。 – AndreaM16