I am building a web application by using react, axios as front end, and sqlite, express, nodejs as the back end.
I am trying to search a student from the server and database, and then modify the name of the student. However, although I made sure my backend should be alright by using postman, it still does not update the row I selected. And I also made sure the object I passed to the server is an object containing only studentId
and firstName
by using console.log
.
This is my react javascript It has two main function:
handleSearch
: Search the student by using thesearchId
from the userhandleModifyFirstName
: Modify the student first name based on thestudentId
, and this is the function that does not work.
import React, { useState } from "react";
import axios from "axios";
const SearchStudent = () => {
const [searchId, setSearchId] = useState("");
const [studentsList, setStudentsList] = useState([]);
const [firstName, setFirstName] = useState("");
const handleSearch = () => {
const newSearchId = searchId;
axios
.get("http://localhost:8080/students/" + newSearchId)
.then((response) => {
setStudentsList(response.data.row);
});
setSearchId("");
setStudentsList([]);
};
const handleModifyFirstName = (studentId) => {
const data = { studentId, firstName };
window.alert(data);
console.log(data);
axios
.post("http://localhost:8080/students/modifyFirstName/", data)
.then((response) => {
var resData = response.data;
let data = JSON.stringify(resData);
window.alert("Response recieved from server = " + data);
});
};
return (
<div>
<form>
<input
type="text"
id="searchId"
name="searchId"
value={searchId}
onChange={(e) => setSearchId(e.target.value)}
></input>
</form>
<button onClick={handleSearch}>search</button>
{studentsList.map((data) => (
<div key={data.studentId}>
<h4>first Name: {data.firstName}</h4>
<p>second name: {data.lastName}</p>
<input
type="text"
id="firstName"
name="firstName"
value={firstName}
onChange={(e) => setFirstName(e.target.value)}
></input>
<button onClick={() => handleModifyFirstName(data.studentId)}>
edit first name
</button>
</div>
))}
</div>
);
};
export default SearchStudent;
This is the server.js
var express = require("express");
var cors = require("cors");
var bodyParser = require("body-parser");
var db = require("./database.js");
var app = express();
app.use(cors());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
var HTTP_PORT = 8080;
app.listen(HTTP_PORT, () => {
console.log("Server running on port %PORT%".replace("%PORT%", HTTP_PORT));
});
app.get("/", (req, res, next) => {
res.json({ message: "Ok" });
});
app.post("/students/modifyFirstName/", (req, res, next) => {
//this is the SQL query that should work
const sql = 'UPDATE students SET firstName =? WHERE studentId =?';
const params = [req.query["firstName"], req.query["studentId"]];
// const params = [data.firstName, data.studentId];
db.run(sql, params, function (err, result) {
if (err) {
res.status(400).json({ error: err.message });
return;
}
res.json({
message: "success",
data: data,
id: this.lastID,
});
});
});
This is the database.js
var sqlite3 = require("sqlite3").verbose();
let db = new sqlite3.Database("students.db", (err) => {
if (err) {
console.error(err.message);
throw err;
}
console.log("Connected to the students database.");
});
const sql =
"CREATE TABLE students (firstName text, lastName text, studentId text) ";
db.run(sql, (err) => {
if (err) {
console.log("Table already created.");
} else {
console.log("Table created.");
console.log("First time Table created, creating some rows.");
var insert =
"INSERT INTO students (firstName, lastName, studentId) VALUES(?,?,?)";
db.run(insert, ["hellow", "world1", "1"]);
db.run(insert, ["hellow", "world2", "2"]);
db.run(insert, ["some", "value", "3"]);
}
});
module.exports = db;
Any help would be appreciated!