首页 > 解决方案 > React - Axios 发布请求返回:状态码 406

问题描述

我对反应比较陌生,目前正在从事一个带有后端的项目。到目前为止,我有多个带有GET, PUT,DELETE请求的组件可以完美地工作。最近几天,我一直在post使用form-data.

我很确定它与configor有关系,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 && errors.name.type==='required' && <span>missing name</span>}
            {errors.name && errors.name.type==='minLength' && <span>name is too short</span>} */}
            {errors.firstName?.type==='required' && <span>missing name</span>}
            {errors.firstName?.type==='minLength' && <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 && <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 && <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 && <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 BeanDto和其他方式。

错误(控制台):

一般的:

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

请求标头:

  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

响应标头:

  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

对于问我为什么使用的你multi-part form data是因为我要添加图像。但是,到目前为止,我只是在测试。

我以前从未遇到过代码问题,406并试图查看人们提出的其他解决方案,但仍然无法解决我的问题。

请问有人可以帮忙吗?

谢谢。

标签: reactjspostaxios

解决方案


推荐阅读