![](/img/trans.png)
[英]How to get data from Laravel backend and display in Vue/Nuxt frontend
[英]Trying to get API data from backend to frontend
我已经从我的React前端创建了一个输入表单,我已经能够使用fetch将这些数据发送到我的服务器。 从这里我可以在我的app.get()中访问它并将表单数据传递给我的API函数,最终当我控制日志结果时,我得到了我想要的结果。 我现在的问题是我正在努力寻找一种方法来从我的前端访问这些数据。
关于在这一点上做什么我很困惑,我想如果我在api函数中做了类似response.send()的东西,它可能有用,但它没有。 据我所知,当您获得数据时,您可以使用POST请求将其发送到特定端点,然后对该特定端点执行get请求以将其恢复,但似乎我无法在这个案例。
//From my front end react page, the front end data is a form:
handleSubmit(event: any){
event.preventDefault();
let location: string = this.state.location
fetch('/', {
method: 'POST',
headers: {
'Content-type': 'application/x-www-form-urlencoded'
},
body: location
})
}
//From my server file:
app.use('/', express.static(path.resolve('client', 'dist')));
app.get('/', (req: any, response:any) => {
let city = Object.keys(req.body)[0]
if (city.match(/[a-zA-z]/g)){
console.log('string')
api.locationToCoords(city, (result:Object) => {
console.log(result)
//response.send()
})
} else {
//Geolocation
let x = city.split(',')
api.retrieveData(x[0], x[1], ((results:any) => {
console.log('~~~~~~~~~~~~~~~~~~~~~~~~~~~')
console.log('results: ',results)
}))
}});
简单的fetch
就是这样,你可以用它来获取前端的数据
fetch('your URL to fetch data', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
// 'Content-Type': 'application/x-www-form-urlencoded',
},
body: formData //if any
})
.then(function(response) {
return response.json();
})
.then(function(myJson) {
console.log(JSON.stringify(myJson));
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.