首页 > 解决方案 > 在javascript中使用post方法时Json文件没有得到更新?

问题描述

这是post的js代码:

async function invoice() {
    const baseurl = 'http://127.0.0.1:8000/api/getInvoice/';
    let response = await fetch(baseurl, {
        method: 'POST',
        body: JSON.stringify({
            userId: 1,
            Total: 3333
        }),
        headers: {
            'Content-type': 'application/json; charset=UTF-8',
        },
    })
    .then((response) => response.json())
    .then((json) => console.log(json));
}

这是后端代码:

public function getInvoice(Request $request){
    $invoice = json_encode($request->all());
    $result = file_put_contents(base_path('storage/app/invoice.json'),$invoice);
}

每次发布时,它只显示一个条目。即内容被另一个覆盖而不是创建新条目?

{
    userId: 1,
    Total: 3333
}

标签: javascriptphphtmllaravelapi

解决方案


试试这个附加到文件而不是仅仅覆盖它:

我已经设置了附加标志并为操作添加了一个锁。在这里阅读更多。

public function getInvoice(Request $request){
    $invoice = json_encode($request->all());
    $result = file_put_contents(base_path('storage/app/invoice.json'), $invoice, FILE_APPEND | LOCK_EX);
}

推荐阅读