Вот мой компонент реакции
import React, { useState } from 'react'
import axios from 'axios';
const Add = () => {
axios.defaults.headers.common['X-Auth-Token'] = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c';
const [product_name, setProduct_name] = useState('');
const [product_image, setProdcut_image] = useState('');
const [product_rate, setProdcut_rate] = useState(0);
const onSelectFile = e => {
setProdcut_image(e.target.files[0]);
}
const handleSubmit = (e) => {
e.preventDefault();
axios
.post('http://localhost/api/addproduct', {
'product_name': product_name,
'product_image': product_image,
'product_rate': product_rate,
})
.then(res => console.log(res))
.catch(err => console.error(err));
}
return (
<div className="container-fluid pt-4">
<form onSubmit={handleSubmit}>
<div className="col-12">
<div className="row">
<div className="col-md-12">
<div className="form-group">
<input type="text" className="form-control" value={product_name} onChange={e => { setProduct_name(e.target.value) }} name="product_name" required placeholder="Product Name" autoFocus />
</div>
<div className="form-group">
<input type="number" className="form-control" value={product_rate} onChange={e => { setProdcut_rate(e.target.value) }} required name="product_rate" placeholder="Rate" />
</div>
<div className="form-group">
<label >Upload Product Image</label>
<input type="file" className="form-control-file" name="product_image" required onChange={onSelectFile} />
</div>
<div className="form-group">
<button type="submit" className="btn btn-success">Add Product</button>
</div>
</div>
</div>
</div>
</form>
</div>
)
}
export default Add
* Вот моя Laravel функция API-хранилища *
<?php
namespace App\Http\Controllers;
use Illuminate\Support\Facades\DB;
use Illuminate\Http\Request;
use App\Product;
use App\Http\Resources\Product as ProductResource;
class AddProductController extends Controller
{
public function store(Request $request)
{
try{
if($request->hasFile('product_image')){
$fileNameWithExt = $request->file('product_image')->getClientOriginalName();
$fileName = pathinfo($fileNameWithExt, PATHINFO_FILENAME);
$extension = $request->file('product_image')->getClientOriginalExtension();
$fileNameToStore = $fileName.'_'.time().'.'.$extension;
$path = $request->file('product_image')->storeAs('public/images', $fileNameToStore);
}
else{
$fileNameToStore = 'noimage.jpg';
}
//Save the data to database
$product = new Product;
$product->product_name = $request->input('product_name');
$product->product_rate = $request->input('product_rate');
$product->product_image = $fileNameToStore;
$product->save();
return new ProductResource($product);
}
catch(Exception $e){
return response()->json([
'success'=>false
]);
}
}
}
* Я получаю сообщение об ошибке, подобное при отправке формы *
dashboardpanel.js:377 POST http://localhost/api/product 422 (Unprocessable Entity)
dispatchXhrRequest @ dashboardpanel.js:377
xhrAdapter @ dashboardpanel.js:211
dispatchRequest @ dashboardpanel.js:857
Promise.then (async)
request @ dashboardpanel.js:634
Axios.<computed> @ dashboardpanel.js:659
wrap @ dashboardpanel.js:1223
handleSubmit @ dashboardpanel.js:38266
callCallback @ dashboardpanel.js:4636
invokeGuardedCallbackDev @ dashboardpanel.js:4685
invokeGuardedCallback @ dashboardpanel.js:4740
invokeGuardedCallbackAndCatchFirstError @ dashboardpanel.js:4754
executeDispatch @ dashboardpanel.js:4837
executeDispatchesInOrder @ dashboardpanel.js:4862
executeDispatchesAndRelease @ dashboardpanel.js:7726
executeDispatchesAndReleaseTopLevel @ dashboardpanel.js:7735
forEachAccumulated @ dashboardpanel.js:7707
runEventsInBatch @ dashboardpanel.js:7752
runExtractedPluginEventsInBatch @ dashboardpanel.js:7962
handleTopLevel @ dashboardpanel.js:8006
batchedEventUpdates$1 @ dashboardpanel.js:26319
batchedEventUpdates @ dashboardpanel.js:5243
dispatchEventForLegacyPluginEventSystem @ dashboardpanel.js:8016
attemptToDispatchEvent @ dashboardpanel.js:8715
dispatchEvent @ dashboardpanel.js:8637
unstable_runWithPriority @ dashboardpanel.js:37095
runWithPriority$1 @ dashboardpanel.js:15487
discreteUpdates$1 @ dashboardpanel.js:26335
discreteUpdates @ dashboardpanel.js:5254
dispatchDiscreteEvent @ dashboardpanel.js:8616
react_devtools_backend.js:6 Error: Request failed with status code 422
at createError (dashboardpanel.js:791)
at settle (dashboardpanel.js:1052)
at XMLHttpRequest.handleLoad (dashboardpanel.js:260)
Я пробовал некоторые методы, которые используют FormData (), но не может решить проблему. Пожалуйста, дайте мне лучшее решение для решения этой проблемы
Я спешу, пожалуйста, дайте мне решение, я устаю от этой ошибки, я могу только переслать свой проект, только исправляя эту ошибку. .................................................. .................................................