无法向我的/注册路线提交发帖请求

时间:2018-12-19 02:34:00

标签: javascript node.js mongodb express

我正在学习如何使用节点设置用户注册注册,但是由于某种原因,每当我发送带有电子邮件和密码的POST请求时,都会收到Postman的404错误消息,提示“无法POST / signup”。我尝试调试代码,但是我看不到为什么会这样。

这是我设置用户的方式。

用户模型

const mongoose = require('mongoose');

const userSchema = mongoose.Schema({
    _id: mongoose.Schema.Types.ObjectId,
    email: { 
        type: String, 
        required: true, 
        unique: true, 
        match: /[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?/
    },
    password: { type: String, required: true }
});

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

用户路线

const express = require("express");
const router = express.Router();
const mongoose = require("mongoose");
const bcrypt = require("bcrypt");

const User = require("../models/user");

router.post("/signup", (req, res, next) => {
  User.find({ email: req.body.email })
    .exec()
    .then(user => {
      if (user.length >= 1) {
        return res.status(409).json({
          message: "Mail exists"
        });
      } else {
        bcrypt.hash(req.body.password, 10, (err, hash) => {
          if (err) {
            return res.status(500).json({
              error: err
            });
          } else {
            const user = new User({
              _id: new mongoose.Types.ObjectId(),
              email: req.body.email,
              password: hash
            });
            user
              .save()
              .then(result => {
                console.log(result);
                res.status(201).json({
                  message: "User created"
                });
              })
              .catch(err => {
                console.log(err);
                res.status(500).json({
                  error: err
                });
              });
          }
        });
      }
    });
});

router.delete("/:userId", (req, res, next) => {
  User.remove({ _id: req.params.userId })
    .exec()
    .then(result => {
      res.status(200).json({
        message: "User deleted"
      });
    })
    .catch(err => {
      console.log(err);
      res.status(500).json({
        error: err
      });
    });
});

module.exports = router;

我的app.js

const express = require('express');
const app = express();
const morgan = require('morgan');
const productRoutes = require('./api/routes/product');
const orderRoutes = require('./api/routes/order');
const userRoutes = require('./api/routes/user');
const bodyParser = require('body-parser');
const mongoose = require('mongoose');

mongoose.connect('mongodb://admin:' +process.env.MONGO_ATLAS_PW+'@cluster0-shard-00-00-xykap.mongodb.net:27017,cluster0-shard-00-01-xykap.mongodb.net:27017,cluster0-shard-00-02-xykap.mongodb.net:27017/test?ssl=true&replicaSet=Cluster0-shard-0&authSource=admin&retryWrites=true', {
    useNewUrlParser: true
});


app.use(morgan('dev'));
app.use('/uploads',express.static('uploads'));
app.use(bodyParser.urlencoded({
    extended: false
}));
app.use(bodyParser.json());
app.use((req, res, next) => {
    res.header('Access-Control-Allow-Origin', '*');
    res.header('Access-Control-Allow-Headers',
    "Origin, X-Requested-With, Content-Type, Accept, Authorization");
    if(req.method === 'OPTIONS'){
        res.header('Access-Control-Allow-Methods', 'PUT, POST, PATCH, DELETE, GET');
        return res.status(200).json({});
    }
    next();
 });
app.use((error, req, res, next) => {
    res.status(error.status || 500);
    res.json({
        error: {
            message: error.message
        }
    });
});
app.use('/products', productRoutes);
app.use('/orders', orderRoutes);
app.use ('/users', userRoutes);
module.exports = app;

2 个答案:

答案 0 :(得分:1)

由于您的注册视图位于userRoutes文件中,因此,由于行'/users',其路径将以app.use ('/users', userRoutes);为前缀。

因此,您的注册视图的完整路径是'/users/signup',而不仅仅是'/signup'

答案 1 :(得分:1)

app.use ('/users', userRoutes);会生成/users/signup路由,因此您应该更改为app.use(userRoutes)