Код: Выделить всё
document.getElementById('userForm').addEventListener('submit', function(event) {
event.preventDefault();
const email = document.getElementById('email').value;
const password = document.getElementById('password').value;
const firstName = document.getElementById('firstName').value;
const lastName = document.getElementById('lastName').value;
const isAdmin = document.getElementById('isAdmin').value;
const xsrfToken = getXSRFToken();
fetch('/admin/users', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-XSRFToken': xsrfToken,
'Accept': 'application/json'
},
body: JSON.stringify({ Email: email, Password: password, First_name: firstName, Last_name: lastName, IsAdmin: isAdmin }),
}).then(console.log(JSON.stringify({ Email: email, Password: password, First_name: firstName, Last_name: lastName, IsAdmin: isAdmin })))
.then(response => {
if(!response.ok){
return response.text().then(text => {
throw new Error(text)
});
}
return response.json();
})
.then(data => {
fetchUsers()
document.getElementById('userForm').reset()
})
.catch((error) => {
console.error('Error while creating the user:', error);
alert('Error while creating the user:', error);
});
});
< /code>
Но в моем контроллере GO: < /p>
func (c *AdminController) AddUser() {
var user models.User
log.Log.Info(string(c.Ctx.Input.RequestBody))
err := json.Unmarshal(c.Ctx.Input.RequestBody, &user)
if err != nil {
log.Log.Critical("Failed to add new user: ", err.Error())
c.Data["json"] = map[string]string{"status": "failed", "message": "Invalid JSON payload"}
c.Ctx.ResponseWriter.WriteHeader(400) // Bad Request
c.ServeJSON()
return
}
err = user.SetPassword(user.Password)
if err != nil {
log.Log.Critical("Failed to hash user password: ", err.Error())
c.Data["json"] = map[string]string{"status": "failed", "message": "Error hashing password: " + err.Error()}
c.Ctx.ResponseWriter.WriteHeader(500) // Internal Server Error
c.ServeJSON()
return
}
o := orm.NewOrm()
_, err = o.Insert(&user)
if err != nil {
log.Log.Critical("Failed to add new user: ", err.Error())
c.Data["json"] = map[string]string{"status": "failed", "message": "Error creating user: " + err.Error()}
c.Ctx.ResponseWriter.WriteHeader(500) // Internal Server Error
c.ServeJSON()
return
}
c.Data["json"] = map[string]string{"status": "success"}
c.ServeJSON()
}
My User model looks like this:
Код: Выделить всё
type User struct {
Id int `orm:"pk;auto";json:"Id"`
First_name string `json:"First_name"`
Last_name string `json:"Last_name"`
Email string `orm:"unique";json:"Email"`
Phone_number string `json:"Phone_number"`
Shipping_address string `json:"Shipping_address"`
Password string `orm:"size(128)";json:"Password"`
Date_registered time.Time `orm:"auto_now_add;type(datetime)";json:"Date_registered"`
IsAdmin bool `orm:"default(false)";json:"IsAdmin`
}
< /code>
Я попытался настроить cors в main.go, чтобы разрешить post, pult, delete и everses: < /p>
beego.InsertFilter("*", beego.BeforeRouter, cors.Allow(&cors.Options{
AllowAllOrigins: true,
AllowMethods: []string{"GET", "POST", "PUT", "DELETE", "OPTIONS"},
AllowHeaders: []string{"Origin", "Authorization", "Access-Control-Allow-Origin", "Content-Type", "X-XSRFToken"},
ExposeHeaders: []string{"Content-Length", "Access-Control-Allow-Origin"},
AllowCredentials: true,
}))
Подробнее здесь: https://stackoverflow.com/questions/795 ... ts-correct