Axios.get 返回纯 html 而非 JSON 返回数据

新手上路,请多包涵

我刚接触 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 许可协议

阅读 2k
2 个回答

将 api url 移动到 php 文件的顶部,最好添加“api/”作为前缀

<?php

Route::post('api/save-product', 'ProductController@saveProduct')->name('save.product');
Route::get('api/getproducts', 'ProductController@products')->name('get.products');

Route::get('{any}', function () {
    return view('welcome');
})->where('any','.*');

Route::get('/', function () {
    return view('welcome');
});

原文由 Sachith Rukshan 发布,翻译遵循 CC BY-SA 4.0 许可协议

在 Axios.get() HTTP 调用中传递附加设置

export const axiosConfig = {
    headers: {
        'Content-Type': 'application/json;charset=UTF-8',
        "Access-Control-Allow-Origin": "*",
        "APITOKEN": API_TOKEN
    }
};

 axios.get('http://localhost:8000/getproducts',axiosConfig)
            .then(response => {
   console.log(response.data);
 });

原文由 vikas dhiman 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题