Within my client-side JavaScript, I have implemented the following function which is executed upon an onclick event:
function submitForm(event) {
const data = { name, image_url };
console.log(data);
fetch('/', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(data),
});
}
This function sends a POST request to the Express.js backend of the application, invoking another function that should render either of two EJS views. Here is the corresponding Express.js function:
router.post('/', function (req, res) {
console.log('hitting router post');
var { name, imageURL } = req.body;
console.log(name, imageURL);
if (nicknameIsAvailable(name)) {
let user = {
nickname: name,
id: '',
image: imageURL,
};
console.log("new user connecting")
res.cookie('nickname', name, { signed: false });
res.render('chat', { nickname: name });
} else {
console.log('rejecting user ' + name + ' as it is already taken');
res.render('index', { message: userTakenErrorMessage });
}
});
The issue here lies in the fact that res.render does not directly render the EJS view. It seems to be returning the HTML markup of the view to the client-side JavaScript instead. To achieve the desired behavior of rendering the "chat" or "index" views with the given arguments, how can this be addressed?
If this specific approach does not yield the intended results, what alternative methods could be explored to add data to the body of a request without relying on a form and then triggering the rendering of a view?