邮递员能够发送POST请求,但不能发送我的前端代码

时间:2019-01-02 14:09:12

标签: javascript mysql fetch-api

我一直在尝试通过我的原始JavaScript前端注册用户,但是无法发出不返回400状态代码的POST请求。另一方面,使用Postman,POST请求可以正常工作,并且用户注册成功。

这是我发出POST请求时记录的内容:

enter image description here

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)}
}

1 个答案:

答案 0 :(得分:0)

请尝试在您的提取调用中将内容类型更改为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));