postman可以发送post请求,但不能发送我的前端代码

jtw3ybtb  于 2021-06-17  发布在  Mysql
关注(0)|答案(1)|浏览(773)

我一直试图通过vanilla javascript前端注册一个用户,但无法发出不返回400状态码的post请求。另一方面,对于postman,post请求工作正常,用户注册成功。
这是我发出post请求时记录的内容:

html格式:

<body>
    <form id="signup-form">
        <h1>Sign up Form</h1>
        <table>
            <tr>
                <td id="yo">User email: </td>
                <td><input type="email" name="email" placeholder="email" /></td>
            </tr>
            <tr>
                <td>Username: </td>
                <td><input type="text" name="username" placeholder="username"/></td>
            </tr>
            <tr>
                <td>Password:</td>
                <td><input type="password" name="password" placeholder="password" /></td>
            </tr>
            <tr>
                <td>Confirm Password:</td>
                <td><input type="password" name="password2" placeholder="password" /></td>
            </tr>
            <tr>
                <td><input type="submit" value="signup";/></td>
            </tr>
        </table>
    </form>
    <p>Already have an account? <a href="index.html "> Login </a></p>
    <script src="signup.js"></script>
</body>

这就是我需要帮助的地方,它为什么返回400响应。前端javascript:

const form = document.getElementById('signup-form'); 
     form.onsubmit = function(e) {
        e.preventDefault();

      const email = form.email.value; 
        const username = form.username.value;
        const password = form.password.value;
        const password2 = form.password2.value; 

        const user = {
            email,
            username,
            password,
            password2,   
        }
          fetch('http://localhost:4002/api/user/register', {
              method: 'POST',
              body: JSON.stringify(user),
              headers:{
              'Content-Type': 'application/json'
              }
          }).then(res => {
             console.log(res); 
          })
          .catch(error => console.error('Error:', error));
         form.reset();
       }

后端代码(如需要):
路线

//Register user
router.post('/register', (req, res, next) => {

      const { errors, isValid } = validateRegisterInput(req.body);
    //Check validation
    if (!isValid) {
        return res
            .status(400)
            .json(errors);
    }

    models.User.findOne({ 
        where: {
        email: req.body.email
        } 
    })
        .then(user => {
            if (user) {
                errors.email = 'Email already exists';
                errors.username = 'Username already exists';
                return res
                    .status(400)
                    .json(errors)
            } else {

                const data = {
                        email: req.body.email,

                        password: req.body.password,

                        username: req.body.username,
                };

                //Encrypting password
                bcrypt.genSalt(10, (err, salt) => {
                    bcrypt.hash(data.password, salt, (err, hash) => {
                        if (err)
                            throw err;
                        data.password = hash;
                        models.User.create(data).then(function(newUser, created) {

                            if (!newUser) {

                                return next(null, false);

                            }

                            if (newUser) {

                                return next(null, newUser);

                            }

                        })
                            .then( user => {
                                res.json(user)
                            })
                            .catch((err) => {
                                console.log(err);
                        })
                    })
                })
            }
        })
});

模型

"use strict";
module.exports = function(sequelize, DataTypes){
    var User = sequelize.define('User', {
        id: {
            allowNull: false,
            autoIncrement: true,
            primaryKey: true,
            type: DataTypes.INTEGER,

        },
        username: {
            type: DataTypes.STRING, 
            validate: {
                len: [2, 20],
                msg: 'Username must be between 2 and 20 characters'
            }
        },
        email: DataTypes.STRING,
        password: {
            type: DataTypes.STRING,
            validate: {
                len: {
                   args: [5],
                   msg: 'Password must be atleast 5 characters'
                }
            }
        }
    });
    User.associate = function(models) {
      //associations can be defined here

    }
   return User; 
};

验证

const Validator = require('validator');
const isEmpty = require('./is-empty');

module.exports = function validatorRegisterInput(data) {
    let errors = {};

        data.username = !isEmpty(data.username)
        ? data.username
        : '';

    data.email = !isEmpty(data.email)
        ? data.email
        : '';
    data.password = !isEmpty(data.password)
        ? data.password
        : '';
    data.password2 = !isEmpty(data.password2)
        ? data.password2
        : '';

    if (Validator.isEmpty(data.email)) {
        errors.email = 'Email field is required';
    }

    if (!Validator.isEmail(data.email)) {
        errors.email = 'Email field is required';
    }

    if (Validator.isEmpty(data.password)) {
        errors.password = 'Password is required';
    }

    if (!Validator.isLength(data.password, {
        min: 5
    })) {
        errors.password = 'Password must be atleast 5 characters';
    }

    return {errors, isValid: isEmpty(errors)}
}
rn0zuynd

rn0zuynd1#

请尝试在fetch调用中将内容类型更改为application/json。表单提交会将整个页面发布回服务器,在这种情况下,您拥有的内容类型可以工作,但您正在进行获取调用并阻止默认行为。

fetch('http://localhost:4002/api/user/register', {
              method: 'POST', // or 'PUT'
              body: JSON.stringify(user), // data can be `string` or {object}!
              headers:{
              'Content-Type': 'application/json'
              }
          }).then(res => {
             document.getElementById("yo").style.color = "red"; 
             console.log(res); 
          })
          .catch(error => console.error('Error:', error));

相关问题