gpt4 book ai didi

node.js - NodeJs 路由不起作用

转载 作者:太空宇宙 更新时间:2023-11-03 23:25:06 24 4
gpt4 key购买 nike

我正在尝试创建一个用于在nodejs中登录的api。但是当我通过Http请求程序检查登录路由时,它显示Cannot“POST/api/authenticate”

项目结构:

enter image description here

server.js 文件:

var express    = require('express');
var app = express();
var port = process.env.PORT||8080;
var morgan = require('morgan');
var mongoose = require('mongoose');
var bodyParser = require('body-parser');
var router = express.Router();
var appRoutes = require('./app/routes/api')(router);
var path = require('path');

app.use(morgan('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(express.static(__dirname + '/public'));
app.use('/app',appRoutes);


mongoose.connect('mongodb://localhost:27017/tutorial', function(err){
if(err) {
console.log('Not connected to the Database: '+ err);
}
else {
console.log('Succesfully connected to Mongodb');
}
});

app.get('*',function(req,res){
res.sendFile(path.join(__dirname + '/public/app/views/index.html'));
});

app.listen(port, function () {
console.log('Running the server on port ' + port);
});

/app/models/user.js:

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

var UserSchema = new Schema({
username: { type: String, lowercase: true, required: true, unique: true },
password: { type: String, required: true },
email: { type: String, lowercase: true, required: true, unique: true }

});

UserSchema.pre('save', function(next) {
var user = this;
bcrypt.hash(user.password, null, null, function(err, hash) {
if (err) return next(err);
user.password = hash;
next();
});
next();
});


module.exports = mongoose.model('User', UserSchema);

/app/routes/api.js:

var User       =require('../models/user');

module.exports = function(router) {
//http://localhost:8080/api/users
//User Registration Route
router.post('/users', function(req,res){
var user = new User();
user.username = req.body.username;
user.password = req.body.password;
user.email = req.body.email;
if (req.body.username == null || req.body.username == '' || req.body.email == null || req.body.email == ''|| req.body.password == null || req.body.password == '' ){
res.send('Ensure Username, Email and Password is provided');

} else {
user.save(function(err){
if(err){
res.send('Username or Email already exist');
}
else {
res.send('User created!!!')
}
});
}

});
//User login Route
//http://localhost:8080/api/authenticate
router.post('/authenticate',function(req,res) {
res.send('Testing the route');
});

return router;
}

最后是 HTTP 请求程序输出(在/app/models/api.js 中注册 api 工作正常)

enter image description here

最佳答案

原因似乎是这样的:

app.use('/app',appRoutes);

这会添加带有 /app 前缀的路由,该前缀应该是 /api:

app.use('/api', appRoutes);

关于node.js - NodeJs 路由不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45320532/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com