Använd express i nodejs för att fixa API:t
T.ex.
https://medium.com/@bipingiri27/crud...l-7ce1d4acb418
Testa:
To create a simple example of HTML communicating with a Node.js Express server to interact with a MySQL database, you need three parts:
1. **HTML Frontend**: This is the user interface where users input data or request data.
2. **Node.js Express Backend**: This acts as the middleman, receiving requests from the HTML frontend, interacting with the MySQL database, and returning responses.
3. **MySQL Database**: This is where your data is stored.
Here's a basic example:
### 1. HTML Frontend (`index.html`)
```html
<!DOCTYPE html>
<html>
<head>
<title>MySQL Data</title>
</head>
<body>
<h1>Data Entry for MySQL</h1>
<form action="/submit-data" method="post">
<input type="text" name="data" placeholder="Enter some data">
<button type="submit">Submit</button>
</form>
</body>
</html>
```
### 2. Node.js Express Backend (`app.js`)
First, install Express and MySQL Node.js modules using npm:
```bash
npm install express mysql
```
Then, create your Express server:
```javascript
const express = require('express');
const mysql = require('mysql');
const bodyParser = require('body-parser');
const app = express();
app.use(bodyParser.urlencoded({ extended: true }));
// MySQL connection
const connection = mysql.createConnection({
host: 'localhost',
user: 'your_username',
password: 'your_password',
database: 'your_database'
});
connection.connect();
app.post('/submit-data', (req, res) => {
const data = req.body.data;
connection.query('INSERT INTO your_table SET ?', {data: data}, (error, results, fields) => {
if (error) throw error;
res.send('Data submitted to MySQL: ' + data);
});
});
app.listen(3000, () => {
console.log('Server is running on port 3000');
});
```
### 3. MySQL Database
You need to have MySQL installed and a database with a table to store the data. For example:
```sql
CREATE DATABASE your_database;
USE your_database;
CREATE TABLE your_table (
id INT AUTO_INCREMENT PRIMARY KEY,
data VARCHAR(255) NOT NULL
);
```
### Running the Example
1. Start your MySQL server and ensure the database and table are set up.
2. Run the Node.js application (`node app.js`).
3. Open `index.html` in a web browser and submit data through the form.
When you submit data via the HTML form, it sends a POST request to the Express server, which then inserts the data into the MySQL database. This is a simplified example and doesn't include error handling or security measures like input validation and sanitization, which are crucial for production applications.
Bara ett snabbt förslag från chatGPT, men a, läs på om express.