React — Возврат запроса на публикацию Axios: Код статуса 406

#reactjs #post #axios

Вопрос:

Я относительно новичок в реагировании и в настоящее время работаю над проектом с бэкэндом. До сих пор у меня есть несколько компонентов с GET PUT DELETE запросом , , которые работают отлично. В последние дни я безуспешно дергал себя за волосы с post помощью запроса form-data .

Я почти уверен, что это как-то связано с config операционной file type системой, так как у меня проблема с моими response данными.

СТОРОНА РЕАКЦИИ:

 function AddCustomer(): JSX.Element {

    const {register, handleSubmit, formState: { errors, isDirty, isValid }} = useForm<CustomerPayloadModel>({
        mode: "onTouched"
      });
    const onSubmit: SubmitHandler<CustomerPayloadModel> = data => console.log(data);
    const history = useHistory();

    useEffect(()=>{
        // If we don't have a user object - we are not logged in
        if(!store.getState().authState.user){
            notify.error('Not logged in');
            history.push("/login")
        }
    }) 

    async function send(customer: CustomerPayloadModel) {
        console.log(customer);
        try{
            const formData = new FormData();
            formData.append("firstName: ",customer.firstName);
            formData.append("lastName: ",customer.lastName);
            formData.append("email: ", customer.email);
            formData.append("password: ",customer.password);

           const headers = {
                'Accept': 'multipart/form-data', 
                "authorization": store.getState().authState.user.token
                }
            const response = await axios.post(globals.adminUrls.addCustomer , formData, {headers});
           
            
            //Sending token with interceptor
            // const response = await tokenAxios.post<CustomerModel>(globals.adminUrls.addCustomer   formData);
            const added = response.data;
            alert(added)
            store.dispatch(customerAddedAction(added)); //With Reduxx
            notify.success(SccMsg.CUSTOMER_ADDED)
            history.push('/home')
            
        }
        catch (err) {
            
            console.log(err);
          //  notify.error(err.message);
        }
    }
    
    return (
        <div className="AddCat Box">
        <h2>Add Customer</h2>
        <form onSubmit={handleSubmit(send)}>
            <label>Name</label> 
            <br/>
            <input type="text" name="name" 
            {...register("firstName",{
                required: true, 
                minLength:2})}/>
                {/* pattern: /^[A-Z].*$/ */}
            <br/>
            {/* {errors.name amp;amp; errors.name.type==='required' amp;amp; <span>missing name</span>}
            {errors.name amp;amp; errors.name.type==='minLength' amp;amp; <span>name is too short</span>} */}
            {errors.firstName?.type==='required' amp;amp; <span>missing name</span>}
            {errors.firstName?.type==='minLength' amp;amp; <span>name is too short</span>}
          
           <br/>

            <label>Last name</label> <br/>
            <input type="text" name="last name" step="0.01" 
            {...register("lastName",
                {
                    required: {
                        value:true,
                        message:'Missing Last name'},
                    min:{
                        value:0,
                        message:'last Name must be greater than zero'}
                }
            )}/>
            <br />
            <span>{errors.lastName?.message}</span>
            <br/>

            <label>Email adress</label> <br/>
            <input type="text" name="email" 
            {...register("email",{required:true} )}/>
         
            <br/>
            {errors.email amp;amp; <span>missing email</span>}
            <br/>

            <label>Password</label> <br/>
            <input type="text" name="password" 
            {...register("password",{
                required: {
                    value:true,
                    message:'Missing Password'},
                })}/>
            <br/>
            {/* {errors.birthday amp;amp; <span>missing birthday</span>} */}
            <span>{errors?.password?.message}</span>
            <br/>
            
            {/* <label>Image</label> <br/>
            <input type="file" name="image" accept="image/*" 
            {...register("image",{required: true})} />
            <br/>
            {errors.image amp;amp; <span>missing image</span>}
            <br/> */}

            {/* <button >Add</button> */}
            <Button type="submit" disabled={!isDirty || !isValid} variant="contained" color="primary">Add Customer</Button>
        </form>
    </div>
);
}

export default AddCustomer;
 

Внутренний Контроллер:

 @PostMapping(
        value = "addCustomer",
        consumes = {MediaType.MULTIPART_FORM_DATA_VALUE},
        produces = {MediaType.APPLICATION_JSON_VALUE}
)
@ResponseStatus(HttpStatus.CREATED)

public void addCustomer(@ModelAttribute CustomerDto customerDto) throws AlreadyExistsException {

    adminService.addCustomer(customerDto);
}
 

Примечание:

У меня есть класс CustomerMapper, который сопоставляет Customer Bean to Dto и наоборот.

ОШИБКА (консоль):

Общая информация:

 Request URL: http://localhost:8080/api/admin/addCustomer/
Request Method: POST
Status Code: 406 
Remote Address: [::1]:8080
Referrer Policy: strict-origin-when-cross-origin
 

Request Headers:

   Accept: multipart/form-data
Accept-Encoding: gzip, deflate, br
Accept-Language: en-US,en;q=0.9
authorization: eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJhZG1pbkBhZG1pbi5jb20iLCJpc3MiOiJBZG1pbmlzdHJhdG9yIiwiZXhwIjoxNjMyNjg4MTM1LCJpYXQiOjE2MzI2ODYzMzV9.88DbtQd-6p3x4LKwrWUhpFmH46eUFN4MCcCE_4JsWaU
Connection: keep-alive
Content-Length: 463
Content-Type: multipart/form-data; boundary=----WebKitFormBoundary4l1UGieACD5DetYR
Host: localhost:8080
Origin: http://localhost:3000
Referer: http://localhost:3000/
sec-ch-ua: "Google Chrome";v="93", " Not;A Brand";v="99", "Chromium";v="93"
sec-ch-ua-mobile: ?0
sec-ch-ua-platform: "Windows"
Sec-Fetch-Dest: empty
Sec-Fetch-Mode: cors
Sec-Fetch-Site: same-site
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/93.0.4577.82 Safari/537.36
 

Response Headers:

   Access-Control-Allow-Headers: Authorization, Origin, Accept, x-auth-token, Content-Type, Access-Control-Request-Method, Access-Control-Request-Headers,
Access-Control-Allow-Methods: GET, OPTIONS, HEAD, PUT, POST, DELETE
Access-Control-Allow-Origin: http://localhost:3000
Cache-Control: no-cache, no-store, max-age=0, must-revalidate
Connection: keep-alive
Content-Length: 0
Date: Sun, 26 Sep 2021 20:37:32 GMT
Expires: 0
Keep-Alive: timeout=60
Pragma: no-cache
X-Content-Type-Options: nosniff
X-XSS-Protection: 1; mode=block
 

For you who is asking why I use multi-part form data is because I am going to add an image. however, so far I am just testing.

I have never had an issue before with code 406 and tried to see other solutions asked by people, still could not solve my problem.

Please can anybody help?

Thanks.