在JavaScript中直接访问数据库并不是一个常见的做法,尤其是在浏览器环境中。由于安全性和架构设计的考虑,前端JavaScript通常不直接与数据库通信。相反,数据交互通常通过后端服务器进行。以下是一些基础概念和相关信息:
// 使用Fetch API发送GET请求
fetch('https://api.example.com/users')
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error('Error:', error));
// 使用Fetch API发送POST请求
fetch('https://api.example.com/users', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ name: 'John', age: 30 })
})
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error('Error:', error));
const express = require('express');
const app = express();
const bodyParser = require('body-parser');
app.use(bodyParser.json());
// 模拟数据库
let users = [];
// GET请求处理
app.get('/users', (req, res) => {
res.json(users);
});
// POST请求处理
app.post('/users', (req, res) => {
const user = req.body;
users.push(user);
res.status(201).json(user);
});
app.listen(3000, () => {
console.log('Server is running on port 3000');
});
const cors = require('cors');
app.use(cors());
通过这种方式,JavaScript可以通过后端API间接访问数据库,确保系统的安全性和可维护性。
领取专属 10元无门槛券
手把手带您无忧上云