在javascript中使用post方法时Json文件未更新?

在javascript中使用post方法时Json文件未更新?,javascript,php,html,laravel,api,Javascript,Php,Html,Laravel,Api,这是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

这是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);
}
每次过帐时,它只显示一个条目。i、 e内容被另一个内容覆盖,而不是创建新条目

{
    userId: 1,
    Total: 3333
}

请尝试将其附加到文件,而不仅仅是覆盖文件:

我已经设置了append标志,并为操作添加了一个锁。阅读更多


您的
getInvoice()
方法需要读取文件并将数据添加到现有数据中。目前,您只需对请求进行编码并覆盖文件。此外,如果它是JSON,您不需要对其进行双重编码吗?
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);
}