node写后台接口,从零开始

1、新建文件夹 (test)

2、cmd模式,cd进入当前文件夹

3、npm init  初始化项目

4、npm install mysql -S  //安装MySQL

  npm install express -S  //安装express框架

  npm install body-parser -S  //安装body-parser插件

  npm install cors -S  //安装跨域的插件

5、在项目根目录下创建index.js文件

  不多说,直接上index.js代码

 1 const express = require("express"); //请求相关
 2 const app = express();
 3 
 4 const cors = require("cors");//跨域的
 5 app.use(cors());
 6 
 7 const mysql = require("mysql");//数据库的
 8 
 9 const connection = mysql.createConnection({
10     host: 'localhost',
11     port: '3306',
12     user: 'root',
13     password: 'root123',
14     database: 'student',
15 });
16 
17 app.get('/api/getStudent', (req, res) => {
18     const sqlStr = 'select * from test';
19     connection.query(sqlStr,(err,results) => {
20         console.log(results);
21         if(err) return res.json({err_code:1,message:'获取失败',affectedRows:0})
22         res.json({
23             err_code:0,message:results,affectedRows:0
24         })
25     })
26 });
27 
28 let server = app.listen('8888', 'localhost', () => {
29     console.log(server.address());
30     let host = server.address().address;
31     let port = server.address().port;
32     console.log("应用实例,访问地址为 http://%s:%s", host, port)
33 });
View Code

 6、cd 到test文件夹下,运行node index.js。至此大功告成

猜你喜欢

转载自www.cnblogs.com/doing-good/p/12016352.html
今日推荐