【发布时间】:2019-10-03 23:30:02
【问题描述】:
我正在 Laravel 中制作一个 api 来与前端的 Vue 进行通信。
首先,我不想在每次加载页面时都向数据库发出请求。
解决方法:第一次请求数据库,保存成json文件然后返回,下一次请求只会发送json文件,没有数据库请求。我会在1天后重生。
问题:一切正常,但响应不是有效的 json 格式。所以 Vue 无法获取 json 文件并渲染页面
代码:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use App\Product;
use Storage;
class ProductController extends Controller
{
public function home ()
{
$file = 'json\products.json';
$fileExists = Storage::disk('local')->exists( $file );
$storagePath = Storage::disk('local')->path( $file );
if ( $fileExists ) {
if ( time () - 86400 < filemtime ($storagePath ) ) {
return Storage::get($file);
}
}
$products = Product::select( 'id' , 'name' , 'code' , 'description' , 'size' , 'weight' , 'pic_url' 'pic_video' 'long_description' )->limit(200)->get();
//Storage::disk('local')->put('json\products.json', json_encode($products, JSON_PRETTY_PRINT) ); //Doesnot Work
Storage::disk('local')->put('json\products.json', response()->json(['products' => $products ])); // Doesnot Work
return response()->json(['products' => $products ] , 200); // This response works , and vue catches and reads perfectly
}
}
已编辑:返回 Storage::get($file);
【问题讨论】:
-
你知道,你可以使用
return ['products' => $products];,它会正确返回 JSON -
这样做? Storage::disk('local')->put('json\products.json', ['products' => $products] ); -> 不起作用。
-
不,我的意思是作为你最后的回报
-
另外,
json\products.json不是有效的文件夹位置 -
不,我的意思是作为你的最终回报 -> 这不是这里的问题。问题出在这里:return Storage::get($file);