#javascript #node.js #express #mern
#javascript #node.js #экспресс #mern
Вопрос:
У меня возникли проблемы с моим node.js экспресс-маршруты. Я действительно новичок и не вижу своей ошибки. Я также читал похожие темы в Stackoverflow, но до сих пор не смог решить эту проблему. Может быть, кто-то может помочь обнаружить ошибку.
Я создал 4 маршрута: home-routes.js , пользовательские маршруты, tech-routes.js , и user-auth.js . Только user-auth.js маршруты продолжают получать ошибку 404 при отправке запроса на http://localhost:8001/api/auth или http://localhost:8001/api/auth/
Это мой server.js
const mongoose = require('mongoose');
mongoose.set('useNewUrlParser', true);
mongoose.set('useFindAndModify', false);
mongoose.set('useCreateIndex', true);
mongoose.set('useUnifiedTopology', true);
const express = require('express');
const router = express.Router();
const { func } = require('joi');
const Joi = require('joi');
const helmet = require('helmet')
const morgan = require('morgan')
const config = require('config');
const debug = require('debug')('app:startup');
const home_routes = require('./api/routes/home-routes');
const technology_routes = require('./api/routes/tech-routes');
const user_routes = require('./api/routes/user-routes');
const user_auth = require('./api/routes/user-auth');
// ======================================
// APP-CONFIG
// ======================================
const app = express();
const port = process.env.PORT || 8001;
const connection_url = `mongodb srv://${username}:${password}@cluster0.zmc6p.mongodb.net/upss-db?retryWrites=trueamp;w=majority`
// ======================================
// DB CONFIG
// ======================================
mongoose.connect(connection_url)
.then(() => console.log('Connected to MongoDB...'))
.catch(err => console.error('Could not connect to MongoDB...', err));
// ======================================
// MIDDLE-WARES
// ======================================
app.use(express.json());
app.use(express.urlencoded({ extended: true })); //parse url key=value to json
app.use(express.static('public')); //static assets inside folder 'public'
app.use(helmet());
// ======================================
// API-ENDPOINTS-PREFIX
// ======================================
app.use('/', home_routes);
app.use('/api/tech', technology_routes);
app.use('/api/user', user_routes);
app.use('./api/auth', user_auth);
//Capture All 404 errors
app.use(function (req, res, next) {
res.status(404).send('Unable to find the requested resource!');
});
// ======================================
// LISTENERS
// ======================================
app.listen(port, () => console.log(`Listening on localhost Port ${port}...`));
И это user-auth.js
const mongoose = require('mongoose');
const express = require('express');
const router = express.Router();
const _ = require('lodash');
const bcrypt = require('bcrypt');
const { User } = require('../models/user-schema');
router.get('/', (req, res) => {
res.status(200).send("GET ALL TECHS");
});
// ======================================
// POST REQUEST
// ======================================
/* CREATE ONE NEW USER */
router.post('/', async (req, res) => {
const { error } = validateEmailPassword(req.body);
if (error) return res.status(400).send(error.details[0].message);
// The user with this email is not found in the DB
let user = await User.findOne({ email: req.body.email });
if (!user) return res.status(400).send('Invalid email or password!');
// Password does not match with our DB
const validPassword = await bcrypt.compare(req.body.password, user.password);
if (!validPassword) return res.status(400).send('Invalid email or password!');
res.send(true);
});
function validateEmailPassword(req) {
const validationSchema = Joi.object({
email: Joi.string().min(5).max(255).required().email(),
password: Joi.string().min(5).max(255).required()
});
return validationSchema.validate(req);
}
module.exports = router;
Другой маршрут, подобный тому, что в user-routes.js работает нормально.
const mongoose = require('mongoose');
const express = require('express');
const router = express.Router();
const _ = require('lodash');
const bcrypt = require('bcrypt');
const { User, validateUser } = require('../models/user-schema');
router.get('/', (req, res) => {
res.status(200).send("GET ALL USERS");
});
/* CREATE ONE NEW USER */
router.post('/', async (req, res) => {
const { error } = validateUser(req.body);
if (error) return res.status(400).send(error.details[0].message);
// Make sure the user not already registered
let user = await User.findOne({ email: req.body.email });
if (user) return res.status(400).send('User already registered!');
user = new User(_.pick(req.body, ['firstName', 'lastName', 'email', 'password']));
const salt = await bcrypt.genSalt(10);
user.password = await bcrypt.hash(user.password, salt);
await user.save();
res.send(_.pick(user, ['_id', 'firstName', 'lastName', 'email']));
});
module.exports = router;
Ответ №1:
Возможно, вы хотите
app.use('/api/auth', user_auth);
нет
app.use('./api/auth', user_auth);
в вашем server.js
файле, как кажется, проблема с опечаткой.