Käytetään esimerkkiä staticApiExample pohjana ja muokataan sovellusta, niin että data haetaan tietokannasta.
- Luo kansio databaseApiExample
- Kopioi staticApiExamplen tiedostot em. kansioon
- Asenna MySQL moduuli komennolla
npm install mysql2
- Luo tiedosto database.js, jossa konfiguroidaan yhteys tietokantaan
- Muokataan book_model.js tiedostoa, niin että data haetaan tietokannasta ja tietokantaan voidaan lisätä, muokata ja poistaa dataa
Tietokanta
Käytetään tietokantaa library ja luodaan käyttäjä tunnus seuraavalla koodilla
CREATE USER 'netuser'@'localhost' IDENTIFIED BY 'netpass';
GRANT ALL ON library.* TO 'netuser'@'localhost';
We will use the staticApiExample as a base and modify the application so that data is fetched from a database instead of a static array.
- Create a folder named databaseApiExample.
- Copy the files from **staticApiExample** into this new folder.
- Install the MySQL module by running the command:
npm install mysql2
- Create a new file named **database.js** to configure the database connection.
- Modify **book_model.js** so that data is retrieved from the database, and allow adding, updating, and deleting data.
Database
We will use a database named library and create a user account with the following SQL commands:
CREATE USER 'netuser'@'localhost' IDENTIFIED BY 'netpass';
GRANT ALL ON library.* TO 'netuser'@'localhost';