[英]Postman able to send POST request but not my frontend code
我一直在嘗試通過我的原始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)}
}
請嘗試在您的提取調用中將內容類型更改為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));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.