ErrorException: Undefined array key 'name' in file
P粉187677012
P粉187677012 2023-08-31 10:33:00
0
1
507
<p>I am working on a customer management system that also tracks customer orders. I have set up a CRUD API to handle reading and writing data from the backend database, but when I try to POST the shopping cart data to the database, I get the following error. </p> <blockquote> <p>quote Error parsing JSON from response: SyntaxError: Unexpected token '<', " is not valid JSON</p> <p>Received the following instead of valid JSON: <!-- ErrorException: undefined array key "name" in file On C:\Users\mjver\OneDrive\Documents\Coding\client-api\routes\api.php Line 238</p> </blockquote> <p>I've checked the input data into the client's $data["name"] array and I don't see any errors. I've checked for misspellings and misspellings and all that, and I'm hoping some fresh eyes can help.</p> <p>My front-end and back-end code snippets are as follows:</p> <p>Call the API call function in api.js: </p> <pre class="brush:php;toolbar:false;">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'); } },</pre> <p>API calls in api.js file: </p> <pre class="brush:php;toolbar:false;">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); }); } },</pre> <p>api.php 文件中的 php 路由:</p> <pre class="brush:php;toolbar:false;">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" ] ]; } });</pre> <p>我的订单模型文件:</p> <pre class="brush:php;toolbar:false;">class Orders extends Model { use HasFactory; protected $fillable = [ 'product', 'qty', 'option', 'orderNo', 'userId', 'price', 'fee', 'date', ]; public function product (){ return $this->hasMany(Product::class); } }</pre> <p>如果您能帮助我解决这个问题,我将不胜感激,因为我已经为此苦苦挣扎了一段时间。</p>
P粉187677012
P粉187677012

reply all(1)
P粉543344381

I managed to figure it out. I console.log(this.cart.name) and found it to be "undefined". After further investigation, I found out that the reason is that state.cart is an array of objects, not just one object. The reason, of course, is that each individual item in the cart should be its own object. So my solution is:

for(let i = 0; i <= this.cart.length - 1; i++){
                try {
                    const order = await APIController.CreateOrder(this.cart[i].name, this.cart[i].qty, this.cart[i].option, this.cart[i].price, this.orderNum, this.cart[i].fee, this.cart[i].date, this.id);
                    if(order){
                        this.clearCart();
                    }
                } catch (error){
                    console.log(error);
                }
            }

Breakdown: Since this.cart is an array and not an object, I have to first use a for loop to get the index of each item in the cart and then call a function that posts the data to the database.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!