问题描述
我有一个运行在端口3000上的本地Node.js服务器.我还有一个使用webpack的前端开发服务器,运行在8080上.Node已连接到MySQL服务器.我的项目结构如下:-
I have a local Node.js server running on port 3000. I have another dev server for front end using webpack, running on 8080. Node is connected to MySQL server. My project structure looks like this:-
SampleProject
-> BackEnd
-> FrontEnd
我使用了webpack-dev-server代理选项来代理从webpack-dev-server(8080)到Node(3000)的请求.
I have used webpack-dev-server proxy option to proxy requests from webpack-dev-server (8080) to Node (3000).
我的webpack.config.js的开发服务器配置如下:-
The dev server configuration my webpack.config.js looks like this:-
devServer: {
proxy: {
'/api': {
target: 'http://localhost:3000'
}
},
historyApiFallback: true,
noInfo: true
}
我已经在services.js中编写了一个Node api
I have written a Node api in services.js
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中,我这样调用服务
And in app.js i call the service like this
app.get('/profile', services.getAllPatientData);
在我的Vue组件文件中,我这样调用api:-
In my Vue component file I call the api like this:-
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对象.
Both the servers are now running. When I open localhost:8080/profile, I see the entire json object on the screen.
浏览器控制台未显示任何对象.但是我的网络说localhost:3000/profile.我在这里做什么错?如何解决此问题并获取数据?
The browser console does not show any object. But my network says localhost:3000/profile. What wrong am I doing here? How can I rectify this issue and get the data?
推荐答案
它正好显示您要求它显示的内容.
it's displaying exactly what you asked it to display.
将axios响应回调更改为如下形式:
change your axios response callback to look like this:
var user = JSON.parse( response.data ).results[0]
this.firstName = user.fname;
this.lastName = user.lname;
this.age = user.age;
这篇关于将数据从Node传递到Vuejs的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!