My current challenge involves creating a HTTP request for a CRUD application using JS. The aim is to add a new user account record to the Logins database. However, every time I attempt this request, it results in a 500 error:
To test this, I have written a simple script:
const axios = require("axios");
var http = axios.create({
baseURL: "http://localhost:8080/",
headers: {
"Content-type": "application/json"
}
});
class UserDataService {
getAll(){
return http.get("/users");
}
get(id){
return http.get(`/users/${id}`);
}
create(data){
return http.post("/users", data);
}
update(id, data){
return http.put(`/users/${id}`, data);
}
delete(id){
return http.delete(`/users/${id}`);
}
findByUsername(username){
return http.get(`/users?username=${username}`);
}
authenticateLogin(data){
console.log(data);
return http.get("/login");
}
}
function main(){
const uds = new UserDataService();
uds.create({
username: "root",
email: "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="b5c7dadac1f5d0dbc7dadb9bd6dad8">[email protected]</a>",
password: "password"
}).catch(err => {
console.log(err);
});
}
main();
This script then goes through users.routes.js
:
router.post("/users", users.create);
And eventually reaches users.controller.js
:
exports.create = (req, res) => {
console.log("User being created");
const user = {
username: req.body.username,
email: req.body.email,
password: crypto.createHash("md5").update(req.body.password).digest("hex")
};
Users.create(user)
.then(data => {
res.send(data)
})
.catch(err => {
res.status(500).send({
message: err.message || "Error occurred when creating a user"
})
});
};
The error message received is as follows:
Error: Request failed with status code 500
at createError (/home/amicharski/WebstormProjects/profrec/node_modules/axios/lib/core/createError.js:16:15)
at settle (/home/amicharski/WebstormProjects/profrec/node_modules/axios/lib/core/settle.js:17:12)
at IncomingMessage.handleStreamEnd (/home/amicharski/WebstormProjects/profrec/node_modules/axios/lib/adapters/http.js:293:11)
at IncomingMessage.emit (node:events:402:35)
at endReadableNT (node:internal/streams/readable:1343:12)
at processTicksAndRejections (node:internal/process/task_queues:83:21) {