POST request to spring boot backend gives 400 bad request

Viewed 529

I've got the following in React/JavaScript:

const uploadImage = (e) => {
    e.preventDefault();

    const uploadData = async () => {

    const token = JSON.parse(localStorage.getItem('token'));

    try {
            data = await axios({
            method: 'post',
            url: 'http://192.168.1.218:8080/api/image/upload',
            data: {
                        data: base64,
                        name: 'file',
                        type: 'image/jpeg'
            },
            headers: {  "Content-Type": "multipart/form-data; boundary=<calculated when request is sent>",
                        "Authorization": `Bearer ${token}` 
                    }
                    
        })
        } catch (error) {
            console.log(error)
        }
      }
      uploadData()
   }

But when I click on the button I get the following in the console:

> xhr.js:177 POST http://192.168.1.218:8080/api/image/upload 400
dispatchXhrRequest  @   xhr.js:177
xhrAdapter  @   xhr.js:13
dispatchRequest @   dispatchRequest.js:52
Promise.then (async)        
request @   Axios.js:61
wrap    @   bind.js:9
uploadData  @   Options.js:40
uploadImage @   Options.js:59
onSubmit    @   Options.js:66
callCallback    @   react-dom.development.js:3945
invokeGuardedCallbackDev    @   react-dom.development.js:3994
invokeGuardedCallback   @   react-dom.development.js:4056
invokeGuardedCallbackAndCatchFirstError @   react-dom.development.js:4070
executeDispatch @   react-dom.development.js:8243
processDispatchQueueItemsInOrder    @   react-dom.development.js:8275
processDispatchQueue    @   react-dom.development.js:8288
dispatchEventsForPlugins    @   react-dom.development.js:8299
(anonymous) @   react-dom.development.js:8508
batchedEventUpdates$1   @   react-dom.development.js:22396
batchedEventUpdates @   react-dom.development.js:3745
dispatchEventForPluginEventSystem   @   react-dom.development.js:8507
attemptToDispatchEvent  @   react-dom.development.js:6005
dispatchEvent   @   react-dom.development.js:5924
unstable_runWithPriority    @   scheduler.development.js:646
runWithPriority$1   @   react-dom.development.js:11276
discreteUpdates$1   @   react-dom.development.js:22413
discreteUpdates @   react-dom.development.js:3756
dispatchDiscreteEvent   @   react-dom.development.js:5889

400 bad request

The request does work in Postman. I've tried adding headers but that gives more errors. Without content-type gives a 500 internal server error. CORS is enabled in the backend.

How do I solve this? Any help is deeply appreciated.

Ps. this is my first question on SO. Sorry if I missed anything.

0 Answers
Related