替换为学生管理系统const express=require('express'); const mysql = require("mysql"); const app = express() const parser = require('body-parser') var jsonParser = parser.json(); app.use(jsonParser) const cors = require("cors"); app.use(cors()); app.post('/axios',(request,res,next)=>{ username=request.body.username.trim() password=request.body.password const connection = mysql.createConnection({ host:"localhost", user:"root", password:"123456", database:"my_db_01", port:3306 }) //数据库信息 connection.connect(); connection.query("select * from users where userName=? ",[username],(err,results,fields)=>{ if(err) throw err; if(results.length >0){ let str = JSON.stringify(results);//对对你进行字符串转换 next() const data={name:'axios'} console.log(results.length) //发送响应体 res.end("1"); } }) //连接数据库 connection.query('insert into users(username,password) value (?,?)',[username,password],(err,results,fields)=>{ if(err) { return(console.log(err.message)); } if(results.affectedRows==1){ //发送响应体 res.end('0') } }) connection.end(); }); app.listen(8080,()=>{ console.log("http://127.0.0.1:8080 has started ..."); });
时间: 2023-07-15 12:11:54 浏览: 77
这段代码是一个使用 Express 和 MySQL 实现的学生管理系统,其中包括了注册和登录功能。
代码解析如下:
1. 引入依赖:
```javascript
const express = require('express');
const mysql = require("mysql");
const parser = require('body-parser');
const cors = require("cors");
const app = express();
const jsonParser = parser.json();
app.use(jsonParser);
app.use(cors());
```
2. 处理 POST 请求:
```javascript
app.post('/axios', (request, res, next) => {
username = request.body.username.trim();
password = request.body.password;
const connection = mysql.createConnection({
host: "localhost",
user: "root",
password: "123456",
database: "my_db_01",
port: 3306
});
// 查询用户是否存在
connection.connect();
connection.query("SELECT * FROM users WHERE username = ?", [username], (err, results, fields) => {
if (err) throw err;
if (results.length > 0) {
let str = JSON.stringify(results);
next();
const data = { name: 'axios' };
console.log(results.length);
res.end("1");
}
});
// 注册用户
connection.query('INSERT INTO users(username, password) VALUES (?, ?)', [username, password], (err, results, fields) => {
if (err) {
return(console.log(err.message));
}
if (results.affectedRows == 1) {
res.end('0');
}
});
connection.end();
});
```
3. 启动服务器:
```javascript
app.listen(8080, () => {
console.log("http://127.0.0.1:8080 has started ...");
});
```
阅读全文