Postman able to send POST request but not my frontend code












0















I've been trying to register a user through my vanilla JavaScript front-end, but have been unable to make a POST request that doesn't return a 400 status code. With Postman on the other hand, POST requests work just fine and the user is registered successfully.



This is what is logged when I make POST request:



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>


This is where I need help as to why it returns a 400 response. Front-end 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();
}


Back-end code incase needed:



Route



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


Model



    "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;
};


Validation



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









share|improve this question

























  • What response are you actually getting?

    – basic
    Jan 2 at 14:12






  • 2





    body: JSON.stringify(user)

    – epascarello
    Jan 2 at 14:13











  • I added the response that I'm getting to the OP.

    – Kacey Okafor
    Jan 2 at 15:40











  • Debugging would be very useful here. Set a breakpoint at the register endpoint function to trace where the 400 Bad Request is emanating from.

    – Olantobi
    Jan 3 at 0:31
















0















I've been trying to register a user through my vanilla JavaScript front-end, but have been unable to make a POST request that doesn't return a 400 status code. With Postman on the other hand, POST requests work just fine and the user is registered successfully.



This is what is logged when I make POST request:



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>


This is where I need help as to why it returns a 400 response. Front-end 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();
}


Back-end code incase needed:



Route



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


Model



    "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;
};


Validation



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









share|improve this question

























  • What response are you actually getting?

    – basic
    Jan 2 at 14:12






  • 2





    body: JSON.stringify(user)

    – epascarello
    Jan 2 at 14:13











  • I added the response that I'm getting to the OP.

    – Kacey Okafor
    Jan 2 at 15:40











  • Debugging would be very useful here. Set a breakpoint at the register endpoint function to trace where the 400 Bad Request is emanating from.

    – Olantobi
    Jan 3 at 0:31














0












0








0








I've been trying to register a user through my vanilla JavaScript front-end, but have been unable to make a POST request that doesn't return a 400 status code. With Postman on the other hand, POST requests work just fine and the user is registered successfully.



This is what is logged when I make POST request:



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>


This is where I need help as to why it returns a 400 response. Front-end 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();
}


Back-end code incase needed:



Route



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


Model



    "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;
};


Validation



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









share|improve this question
















I've been trying to register a user through my vanilla JavaScript front-end, but have been unable to make a POST request that doesn't return a 400 status code. With Postman on the other hand, POST requests work just fine and the user is registered successfully.



This is what is logged when I make POST request:



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>


This is where I need help as to why it returns a 400 response. Front-end 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();
}


Back-end code incase needed:



Route



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


Model



    "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;
};


Validation



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






javascript mysql fetch-api






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Jan 2 at 15:09







Kacey Okafor

















asked Jan 2 at 14:09









Kacey OkaforKacey Okafor

135




135













  • What response are you actually getting?

    – basic
    Jan 2 at 14:12






  • 2





    body: JSON.stringify(user)

    – epascarello
    Jan 2 at 14:13











  • I added the response that I'm getting to the OP.

    – Kacey Okafor
    Jan 2 at 15:40











  • Debugging would be very useful here. Set a breakpoint at the register endpoint function to trace where the 400 Bad Request is emanating from.

    – Olantobi
    Jan 3 at 0:31



















  • What response are you actually getting?

    – basic
    Jan 2 at 14:12






  • 2





    body: JSON.stringify(user)

    – epascarello
    Jan 2 at 14:13











  • I added the response that I'm getting to the OP.

    – Kacey Okafor
    Jan 2 at 15:40











  • Debugging would be very useful here. Set a breakpoint at the register endpoint function to trace where the 400 Bad Request is emanating from.

    – Olantobi
    Jan 3 at 0:31

















What response are you actually getting?

– basic
Jan 2 at 14:12





What response are you actually getting?

– basic
Jan 2 at 14:12




2




2





body: JSON.stringify(user)

– epascarello
Jan 2 at 14:13





body: JSON.stringify(user)

– epascarello
Jan 2 at 14:13













I added the response that I'm getting to the OP.

– Kacey Okafor
Jan 2 at 15:40





I added the response that I'm getting to the OP.

– Kacey Okafor
Jan 2 at 15:40













Debugging would be very useful here. Set a breakpoint at the register endpoint function to trace where the 400 Bad Request is emanating from.

– Olantobi
Jan 3 at 0:31





Debugging would be very useful here. Set a breakpoint at the register endpoint function to trace where the 400 Bad Request is emanating from.

– Olantobi
Jan 3 at 0:31












1 Answer
1






active

oldest

votes


















0














Please try changing the content type to application/json in your fetch call. A form submit would post the entire page back to the server in which case the content type you have would work but you are making a fetch call and preventing the default behavior.



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





share|improve this answer

























    Your Answer






    StackExchange.ifUsing("editor", function () {
    StackExchange.using("externalEditor", function () {
    StackExchange.using("snippets", function () {
    StackExchange.snippets.init();
    });
    });
    }, "code-snippets");

    StackExchange.ready(function() {
    var channelOptions = {
    tags: "".split(" "),
    id: "1"
    };
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function() {
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled) {
    StackExchange.using("snippets", function() {
    createEditor();
    });
    }
    else {
    createEditor();
    }
    });

    function createEditor() {
    StackExchange.prepareEditor({
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader: {
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    },
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    });


    }
    });














    draft saved

    draft discarded


















    StackExchange.ready(
    function () {
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f54007817%2fpostman-able-to-send-post-request-but-not-my-frontend-code%23new-answer', 'question_page');
    }
    );

    Post as a guest















    Required, but never shown

























    1 Answer
    1






    active

    oldest

    votes








    1 Answer
    1






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    0














    Please try changing the content type to application/json in your fetch call. A form submit would post the entire page back to the server in which case the content type you have would work but you are making a fetch call and preventing the default behavior.



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





    share|improve this answer






























      0














      Please try changing the content type to application/json in your fetch call. A form submit would post the entire page back to the server in which case the content type you have would work but you are making a fetch call and preventing the default behavior.



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





      share|improve this answer




























        0












        0








        0







        Please try changing the content type to application/json in your fetch call. A form submit would post the entire page back to the server in which case the content type you have would work but you are making a fetch call and preventing the default behavior.



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





        share|improve this answer















        Please try changing the content type to application/json in your fetch call. A form submit would post the entire page back to the server in which case the content type you have would work but you are making a fetch call and preventing the default behavior.



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






        share|improve this answer














        share|improve this answer



        share|improve this answer








        edited Jan 3 at 0:16

























        answered Jan 2 at 14:56









        Andrew FelderAndrew Felder

        512




        512
































            draft saved

            draft discarded




















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f54007817%2fpostman-able-to-send-post-request-but-not-my-frontend-code%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            'app-layout' is not a known element: how to share Component with different Modules

            android studio warns about leanback feature tag usage required on manifest while using Unity exported app?

            WPF add header to Image with URL pettitions [duplicate]