将数据从Node传递到Vuejs

时间:2017-08-07 18:44:25

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

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

SampleProject
  -> BackEnd
  -> FrontEnd

我使用了webpack-dev-server proxy选项来代理从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。我在这做什么错?如何纠正此问题并获取数据?

1 个答案:

答案 0 :(得分:2)

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

将您的axios响应回调更改为:

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