前后端数据流初探

版权声明:@copyright by taorui https://blog.csdn.net/weixin_42541498/article/details/81092898

前后端数据流初探

前端用vue,后端用node.js,数据库用MongoDB

一 启动MongoDB服务器

为了从命令提示符下运行 MongoDB 服务器,你必须从 MongoDB 目录的 bin 目录中执行 mongod.exe 文件。

我的mongoDB安装在F盘的software文件夹里面

在cmd中执行:C:\Users\admin>F:\software\MongoDB\Server\4.0\bin\mongod --dbpath F:\mongoData\db

参考教程:http://www.runoob.com/mongodb/mongodb-window-install.html

打开mangoDB管理工具链接它的默认端口——27017。

二 node.js写接口

先新建一个项目文件,用npm init初始化。然后npm install express,使用express框架。启用8081端口

var server = app.listen(8081, function () {
 
  var host = server.address().address
  var port = server.address().port
 
  console.log("应用实例,访问地址为 http://%s:%s", host, port)                                                                                                                                                                                  
 
})

以getSurveyList接口(获取数据)为例,node.js如下操作MongoDB数据库。

var url = "mongodb://localhost:27017/mydatabase";
app.get('/getSurveyList', function (req, res) {
    MongoClient.connect(url, function(err, db) { //连接数据库
        if (err) throw err;
        var dbo = db.db("mydatabase");
        dbo.collection("surveyTable"). find({}).toArray(function(err, result) { // 返回集合中所有数据
            if (err) throw err;
            console.log(result);
            db.close();
            res.send(JSON.stringify(result));
        });
    });
})

三 前端拿到接口获取数据

前端用的是vue-cli搭建的项目,首先前端启用的是8080接口。直接请求localhost:8081/getSurveyList会存在跨域

服务器代理跨域:在config文件夹的index.js文件中找到dev的属性

 dev: {
    // Paths
    assetsSubDirectory: 'static',
    assetsPublicPath: '/',
    proxyTable: {
    'http://127.0.0.1:8080': {
        target: 'http://127.0.0.1:8081',//请求的目标url
        changeOrigin: true,
        pathRewrite: {
          '^/api': '/api'
        }
      }
    },

使用axios的get方法: 

export const getSurveyList = () => axios.get(url + 'getSurveyList?time=' +  (new Date()).getTime());

vue组件中拿数据: 

 created() {
    this._getSurveyList();
  },
  methods:{
    _getSurveyList() {
      getSurveyList().then(res => {
        this.surveylist = res.data;
        console.log(res);
      })
    },

猜你喜欢

转载自blog.csdn.net/weixin_42541498/article/details/81092898
今日推荐