【问题标题】:Passing data from Node to Vuejs将数据从 Node 传递到 Vuejs
【发布时间】:2018-01-15 03:55:23
【问题描述】:

我有一个本地 Node.js 服务器在端口 3000 上运行。我有另一个使用 webpack 的前端开发服务器,在 8080 上运行。节点连接到 MySQL 服务器。我的项目结构如下:-

SampleProject
  -> BackEnd
  -> FrontEnd

我使用 webpack-dev-server 代理选项将请求从 webpack-dev-server (8080) 代理到 Node (3000)。

我的 webpack.config.js 的开发服务器配置如下所示:-

devServer: {
    proxy: {
        '/api': {
            target: 'http://localhost:3000'
        }
    },
    historyApiFallback: true,
    noInfo: true
}

我在 services.js 中写了一个 Node api

exports.getAllPatientData = function(req, res) {

con.connection.query("SELECT fname, lname, city, country_code, TIMESTAMPDIFF(YEAR, DOB, CURDATE()) AS age FROM sbds_patient_data where pid = 1", function(err, result, fields) {
    if (err) {
        throw err;
        res.json({ status: "error", message: "An error has occurred. Please try again later" });
    }

    console.log(result);
    res.json({ status: "success", results: result });
});}

在 app.js 中我这样调用服务

app.get('/profile', services.getAllPatientData);

在我的 Vue 组件文件中,我这样调用 api:-

import axios from 'axios';

export default{
    data(){
        return{
            firstName: '',
            lastName: '',
            age: '',
            errors: []
        }
    },

    created: function(){
        this.getPatientInfo();
    },

    methods:{

        // Function to get the patient's personal information 
        getPatientInfo: function(){
            axios.get('http://localhost:3000/profile')
            .then(response =>{
                this.firstName = response.data;
                    this.lastName = response.data;
                    this.age = response.data;
            })
            .catch(e => {
                this.errors.push(e);
            })
        }
    }
}

两台服务器现在都在运行。当我打开 localhost:8080/profile 时,我在屏幕上看到了整个 json 对象。

浏览器控制台不显示任何对象。但我的网络显示 localhost:3000/profile。我在这里做错了什么?如何解决此问题并获取数据?

【问题讨论】:

    标签: json node.js webpack vue.js vuejs2


    【解决方案1】:

    它正在显示您要求它显示的内容。

    将您的 axios 响应回调更改为如下所示:

    var user = JSON.parse( response.data ).results[0]
    this.firstName = user.fname;
    this.lastName = user.lname;
    this.age = user.age;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-09-20
      • 2018-08-19
      • 2020-09-21
      • 2019-03-22
      • 2020-12-29
      • 2019-09-30
      相关资源
      最近更新 更多