I’ve done this 100 times, but I’m not sure what’s going on in this instance… I send login creds from my page to an express server:
async function request(url, data) {
data = JSON.stringify(data);
const response = await fetch(url, {
method: "POST",
cache: "no-cache",
headers: {
"Content-Type": "application/json",
},
body: data,
});
console.log('response', JSON.stringify(response));
return response.json();
}
$("#log-form").submit(async () => {
const data = {
username: $('input[name=log-user]').val(),
password: $('input[name=log-pass]').val()
};
const result = await request("/login", data);
console.log("log-result", JSON.stringify(result));
if (result.status == "ok") {
alert("You have successfully logged in!");
} else {
alert(result.error);
}
//window.location.href = "/chat";
});
The express server gets the data as it should, but never seems to send a response back to the page:
app.use(express.json());
app.use(express.urlencoded({extended: true}));
app.post('/login', async (req, res) => {
const username = req.body.username;
const password = req.body.password;
const errString = "Incorrect usernane/password combo.";
let result = await query("SELECT * FROM User WHERE name = '"+username+"'");
result = result[0];
if (result.user_id) {
const valid = await bcrypt.compare(password, result["password"]);
console.log('validPass', valid);
if (valid) {
// login and set session
data.status = "ok";
data.data.user = result;
//req.session.user = result;
} else {
// invalid password
data.status = "error";
data.error = errString;
}
} else {
// invalid password
data.status = "error";
data.error = errString;
}
console.log('data', data);
res.status(200).send(data);
});
The console.log('data', data);
line prints what it should, but neither res.json(data)
nor res.send(data)
are working. I get nothing in the browser console except the original request. No response. What am I doing wrong?