[英]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.