Problem:
The first ajax call in the main.js
is functioning correctly, but there seems to be an issue with the second one. Although it appears to be working initially, I suspect that there may be a bug present. Upon clicking the button, I am able to access the getProducts
method. However, the content of the product_list.html
file does not display on the browser screen as expected. No error messages are displayed on either the front-end or the back-end.
My observation: When I click the button and navigate to F12 -> Network -> products, I notice a status code 200 indicating success along with the content of the product_list.html file in the response.
If the POST ajax call is successful and the line
location.href = "/products";
is added, the browser will load the product_list.html
. I am using the GET ajax call because I need to include the jwt token in the request header. (I have omitted the jwt authentication parts from the code below because I believe the issue lies within the relationship between $.ajax()
and res.sendFile()
)
//routes.js
routes.get("/products", ProductController.getProducts);
//ProductController.js
var root = path.join(__dirname, '../../views');
module.exports = {
getProducts(req, res){
console.log("getProducts!"); //This log appears
res.sendFile("product_list.html", {root}) //HTML is not rendered
},
}
//main.js
$("#btn-login").click(function(){
$.ajax({
type: 'POST',
url: "http://localhost:8000/login",
dataType: "json",
contentType: "application/json",
data: JSON.stringify({
"username": $("#login-user").val(),
"password": $("#login-pwd").val(),
}),
success: function(data){
if ($("#login-chkbx").is(':checked')){
$.ajax({
url: "http://localhost:8000/products",
type: 'GET',
beforeSend: function (xhr) {
xhr.setRequestHeader("user", localStorage.getItem("user"));
},
});
}
}else{
console.log("Checkbox is not checked");
}
}
});
});
What is causing this issue and how can it be resolved?
Thank you!