javascript 错误异常:文件中未定义的数组"键名"

kb5ga3dv  于 2023-06-04  发布在  Java
关注(0)|答案(1)|浏览(100)

我正忙碌一个客户管理系统,它也跟踪客户订单。我已经设置了一个API来处理后端数据库数据的阅读,但是当我尝试将购物车数据POST到数据库时,我得到了以下错误。
quote解析响应中的JSON时出错:语法错误:意外的标记“|”不是有效的JSON
接收以下内容而不是有效的JSON:<!-- ErrorException:Undefined array key“name”in file C:\Users\mjver\OneDrive\Documents\Coding\client-api\routes\api.php on line 238
我已经将输入数据检入到客户端的$data[“name”]数组中,没有发现任何错误。我已经检查了错别字和拼写错误和所有的,我希望一些新鲜的眼睛可以帮助。
我在前端和后端的代码片段如下:
调用api.js中的API调用函数:

async sendOrder(){
            console.log(this.cart);
            
            const order = await APIController.CreateOrder(this.cart.name, this.cart.qty, this.cart.option, this.cart.price, this.orderNum, this.cart.fee, this.cart.date, this.id);
            if(order){
                store.dispatch('clearCart');
            }
        },

api.js文件中的API调用:

CreateOrder: (name, qty, option, price, orderNo, fee, date, userId) => {
        let responseClone;
        const csrfToken = document.cookie.match(/XSRF-TOKEN=([^;]+)/)[1];
        if(
            name == "" ||
            qty == "" ||
            option == "" ||
            price == "" ||
            orderNo == "" ||
            date == "" ||
            userId == ""
        ) {
            return false;
        } else {

            return fetch(API_BASE + "/orders/create", {
                method: "POST",
                headers: {
                    "Content-Type": "application/json",
                    "X-CSRF-TOKEN": csrfToken
                },
                body: JSON.stringify({ name, qty, option, price, orderNo, fee, date, userId })
            }).then((response) => {
                responseClone = response.clone();
                return response.json()
            })
            .then(data => {
                if(data.success){
                    alert("Order created successfully!")
                    return true;
                } else {
                    throw data.response.error;
                }
            }, (rejectionReason) => {
                console.log('Error parsing JSON from response: ', rejectionReason, responseClone);
                responseClone.text()
                .then((bodyText) => {
                    console.log('Receiving the following instead of valid JSON: ', bodyText);
                });
            }).catch(err => {
                alert(err);
            });
        }
    },

api.php文件中的php路由:

Route::post('/orders/create', function(Request $request){
    $data = $request->all();

    if(!Orders::where('orderNo', '=', $data['orderNo'])->exists()){
        $order = Orders::create([
            "name" => $data["name"],
            "qty" => $data["qty"],
            "option" => $data["option"],
            "orderNo" => $data["orderNo"],
            "userId" => $data["userId"],
            "price" => $data["price"],
            "fee" => $data["fee"],
            "date" => $data["date"],
        ]);

        if(empty($order->id)){
            return [
                "success" => false,
                "response" => [
                    "error" => "An unusual error has occured"
                ]
            ];
        } else {
            return [
                "success" => true,
                "response" => [
                    "order" => $order
                ]
            ];
        }
    } else {
        return [
            "success" => false,
            "response" => [
                "error" => "The inventory item already exists"
            ]
        ];
    }
});

我的订单模型文件:

class Orders extends Model
{
    use HasFactory;

    protected $fillable = [
        'product',
        'qty',
        'option',
        'orderNo',
        'userId',
        'price',
        'fee',
        'date',
    ];

    public function product (){
        return $this->hasMany(Product::class);
    }
}

我会很感激任何帮助这个问题,因为我一直在与这个问题斗争了一段时间。

eit6fx6z

eit6fx6z1#

在api.php文件中的php路由中尝试此操作,因为在查询中调用的是“name”列而不是“product”

Route::post('/orders/create', function(Request $request){
    $data = $request->all();

    if(!Orders::where('orderNo', '=', $data['orderNo'])->exists()){
        $order = Orders::create([
            "product" => $data["name"],
            "qty" => $data["qty"],
            "option" => $data["option"],
            "orderNo" => $data["orderNo"],
            "userId" => $data["userId"],
            "price" => $data["price"],
            "fee" => $data["fee"],
            "date" => $data["date"],
        ]);

        if(empty($order->id)){
            return [
                "success" => false,
                "response" => [
                    "error" => "An unusual error has occured"
                ]
            ];
        } else {
            return [
                "success" => true,
                "response" => [
                    "order" => $order
                ]
            ];
        }
    } else {
        return [
            "success" => false,
            "response" => [
                "error" => "The inventory item already exists"
            ]
        ];
    }
});

相关问题