我刚接触 js 并尝试使用 axios.get
在 componentDidmount 时从数据库中获取数据。这是我尝试获取产品的请求。我正在使用与 laravel 的反应。
componentDidMount() {
axios.get('http://localhost:8000/getproducts')
.then(response => {
console.log(response.data);
});
}
在 Controller 中我返回数据
public function products()
{
$products = Product::all();
return response()->json($products);
}
在 axios.get
中返回响应后,我得到以下纯 HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Learn React</title>
<!-- Fonts -->
<link href="https://fonts.googleapis.com/css?family=Nunito:200,600" rel="stylesheet">
<link href="http://localhost:8000/css/app.css" rel="stylesheet">
</head>
<body>
<div id="crud-app"></div>
<script src="http://localhost:8000/js/app.js"></script>
</body>
</html>
网站.php
<?php
Route::get('{any}', function () {
return view('welcome');
})->where('any','.*');
Route::get('/', function () {
return view('welcome');
});
Route::post('save-product', 'ProductController@saveProduct')->name('save.product');
Route::get('getproducts', 'ProductController@products')->name('get.products');
原文由 Arslan Akram 发布,翻译遵循 CC BY-SA 4.0 许可协议
将 api url 移动到 php 文件的顶部,最好添加“api/”作为前缀