Node.js之 express写后端接口

参考

https://blog.csdn.net/studysinklc/article/details/103166451

1 首先,新建一个Node.js项目,在项目目录下安装express

npm install express --save

2 可以用express来建立一个最简单的后端server服务

新建一个server.js文件

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!'));

3 在命令行里用 Node server.js 启动

Node.js之 express写后端接口_第1张图片
访问成功

跨域

为了能在前端调用,必须实现跨域,我们采用Node.js里的cors模块在后端实现跨域

安装cors模块

npm install cors --save

在server.js里调用cors模块

const cors = require('cors');
app.use(cors());

同时我们新加一个test接口,依然是用get方法,返回一个json,供前端调用

app.get('/test', cors(), (req, res, next) => res.json({msg: 'This is a cros test.'}));

完整 server.js

const express = require('express');

const cors = require('cors');

const app = express();

const bodyParser = require('body-parser');

// 调用 cors模块

app.use(cors());

app.use(bodyParser.json());

// 下面是接口 
// http://127.0.0.1:3000/

app.get('/', (req, res) => res.send('Hello!'))

app.get('/get-test', cors(), (req, res, next) => res.json({msg: 'This is a cros test.'}));

app.post('/post-test2', cors(), (req, res, next) => {
    res.setHeader('Content-Type', 'text/plain');
    res.write("your post is: \n");
    res.end(JSON.stringify(req.body));
});


app.listen(3000, () => console.log('Example app listening on port 3000!'));

调用本地数据库

参考 https://blog.csdn.net/qq_45152044/article/details/122310270

1 在终端输入:npm i mysql

2 使用mysql模块 (在js文件中编写)

//引入mysql模块
const mysql = require('mysql');

//配置mysql访问方式
const db = mysql.createConnection({
  host:'localhost',
  user:'root',
  //你的mysql密码
  password:'root',
  //你要连接的数据库
  database:'mydb'
});

//接收前端的数据   第一个是接口的名字
app.get('/login',function(request,response){
	  // request 请求,前端向后端请求
	  // response后台给前端的反馈
	  // request.query  前端发过来的get请求数据
  
  //查询语句
  const sql = `select * from user1 where username='${request.query.username}' and password = '${request.query.password}'`
  //在数据库中查询,err是错误信息,data是查询后的结果以对象的形式返回
  db.query(sql,function(err,data){
    if(err){
       console.log(err)
    }else{
      //data.length=1,即长度为1,直接简写
      if(data.length){
        //输入正确登录成功
        response.send({code:200,msg:'登录成功!'})
      }else{
      	//输入账号密码错误
        response.send({code:500,msg:'账号密码错误'})
      }
    }
  })

结果

Node.js之 express写后端接口_第2张图片
读取本地json文件

app.js 同 上面的 server.js ,启动命令 node app.js

const fs = require("fs"); // 文件模块
const path = require("path"); // 系统路径模块

const express = require("express"); // node.js Web 应用框架
const bodyParser = require("body-parser"); // node.js 中间件,用于处理 JSON, Raw, Text 和 URL 编码的数据

const app = express();
app.use(bodyParser.json()); // 返回一个只解析 json 的中间件,最后保存的数据都存放在 request.body 对象上
app.use(
  bodyParser.urlencoded({
    extended: true
  })
); // 返回的对象为任意类型

// 设置跨域访问
app.all("*", function(request, response, next) {
  response.header("Access-Control-Allow-Origin", "*"); // 设置跨域的域名,* 代表允许任意域名跨域
  response.header("Access-Control-Allow-Headers", "X-Requested-With");
  response.header(
    "Access-Control-Allow-Methods",
    "PUT,POST,GET,DELETE,OPTIONS"
  );
  response.header("X-Powered-By", " 3.2.1");
  response.header("Content-Type", "application/json;charset=utf-8");
  next();
});

// get 首页数据
app.get("/api/index.json", (request, response) => {
  request.statusCode = 200;
  const file = path.join(__dirname, "./api/index.json");
  fs.readFile(file, "utf-8", (err, data) => {
    if (err) {
      response.send("文件读取失败!");
    } else {
      response.send(data);
    }
  });
});

// get 城市列表数据
app.get("/api/city.json", (request, response) => {
  request.statusCode = 200;
  const file = path.join(__dirname, "./api/city.json");
  fs.readFile(file, "utf-8", (err, data) => {
    if (err) {
      response.send("文件读取失败!");
    } else {
      response.send(data);
    }
  });
});

// get 详情页数据
app.get("/api/detail.json", (request, response) => {
  request.statusCode = 200;
  const file = path.join(__dirname, "./api/detail.json");
  fs.readFile(file, "utf-8", (err, data) => {
    if (err) {
      response.send("文件读取失败!");
    } else {
      response.send(data);
    }
  });
});

// 配置服务端口

const hostname = "localhost";
const port = 8082;
const server = app.listen(port, hostname, () => {
  console.log(`服务器运行在 http://${hostname}:${port}`);
});

// const hostname = '127.0.0.1';
// const port = 3000;
// const server = app.listen(port,hostname, () => {
//   console.log(`服务器运行在 http://${hostname}:${port}`);
// });

读取的 json文件 为 新建api中的 index.json 等等json文件

{
"ret": true,
"data": {
    
    "swiperList": [{
            "id": "001",
            "src": "https://th.wallhaven.cc/small/96/96w8e8.jpg"
        },
        {
            "id": "002",
            "src": "https://th.wallhaven.cc/small/13/13mk9v.jpg"
        }
    ],
    "iconList": [{
            "id": "001",
            "imgSrc": "http://img1.qunarzz.com/piao/fusion/1803/95/f3dd6c383aeb3b02.png",
            "txt": "景点门票"
        },
        {
            "id": "002",
            "imgSrc": "http://mp-piao-admincp.qunarzz.com/mp_piao_admin_mp_piao_admin/admin/20193/f0f00d6dfe038c044dbc9a437f58b0eb.png",
            "txt": "一日游"
        }
    ],
    "recommendList": [
        {
          "id": "001",
          "imgUrl":
            "http://img1.qunarzz.com/sight/p0/1902/84/84696f368bbec10da3.img.jpg_200x200_50323152.jpg",
          "infoTit": "北京世界园艺博览会",
          "infoTxt": "80条评论",
          "infoMoney": "108"
        },
        {
          "id": "002",
          "imgUrl":
            "http://img1.qunarzz.com/sight/p0/1409/19/adca619faaab0898245dc4ec482b5722.jpg_200x200_1bc99086.jpg",
          "infoTit": "故宫",
          "infoTxt": "659条评论",
          "infoMoney": "60"
        }
      ],
      "weekendList": [
        {
          "id": "001",
          "imgUrl":
            "http://img1.qunarzz.com/sight/source/1603/6d/2f67ae0659f41f.jpg_r_640x214_bf6cbd0b.jpg",
          "infoTit": "北京赏花好地方",
          "infoTxt": "乱花渐欲迷人眼,京城赏花大搜索"
        },
        {
          "id": "002",
          "imgUrl":
            "http://img1.qunarzz.com/sight/source/1811/f3/86173f863bef61.jpg_r_640x214_52b003ac.jpg",
          "infoTit": "京城周末撒欢",
          "infoTxt": "在帝都过周末,不仅仅是城中游!"
        }
      ]
}
}

你可能感兴趣的:(node.js,npm,前端)