隨著互聯網時代的到來,Web應用程序的開發也變得越來越重要。本文將會介紹如何使用Express和MySQL構建高效的Web應用程序。
一、搭建環境
在使用Express和MySQL構建Web應用程序之前,我們需要確保我們的計算機上已經安裝了Node.js和MySQL。如果沒有安裝,請先去官網下載和安裝。
npm install express --save
npm install mysql --save
二、創建Express應用程序
使用Express框架可以方便快捷地創建Web應用程序。
const express = require('express');
const app = express();
app.get('/', (req, res) => {
res.send('Hello World!');
});
app.listen(3000, () => {
console.log('Example app listening on port 3000!');
});
三、連接MySQL資料庫
在使用MySQL之前,需要先創建一個資料庫。
CREATE DATABASE mydb;
接下來,我們可以在Node.js中使用MySQL模塊連接到資料庫。
const mysql = require('mysql');
const con = mysql.createConnection({
host: "localhost",
user: "yourusername",
password: "yourpassword",
database: "mydb"
});
con.connect(function(err) {
if (err) throw err;
console.log("Connected!");
});
四、基本操作CRUD
通過以下代碼實現增刪改查的基本操作。
4.1查詢
app.get('/users', function (req, res) {
con.query('SELECT * FROM users', function (error, results) {
if (error) throw error;
res.send(results)
});
});
4.2插入
app.post('/users', function(req, res) {
const user = req.body;
con.query('INSERT INTO users SET ?', user, function(error, result) {
if (error) throw error;
res.send(result);
});
});
4.3修改
app.put('/users/:id', function(req, res) {
const id = req.params.id;
const user = req.body;
con.query('UPDATE users SET ? WHERE id = ?', [user, id], function(error, result) {
if (error) throw error;
res.send(result);
});
});
4.4刪除
app.delete('/users/:id', function (req, res) {
const id = req.params.id;
con.query('DELETE FROM users WHERE id = ?', id, function(error, result) {
if (error) throw error;
res.send(result);
});
});
五、總結
通過本文的介紹,我們可以使用Express和MySQL構建高效的Web應用程序。其中,我們了解了如何使用Express框架和MySQL模塊創建一個基本的Web應用程序,並實現了增刪改查等基本操作。
原創文章,作者:UJZY,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/138633.html