简体   繁体   中英

React axios put request returns error 500

axios.put('http://1.1.1.1:1010/api/data', {
    data: {
        ip: '123123',
        smth: true
    },
    headers: {
        'content-type': "application/json ",
        'Access-Control-Allow-Origin': '*',
    },
}).then(res => {
    console.log(res)
}).catch(error => {
    console.log(error);
})

I recieved

Error: Request failed with status code 500

Get request works fine. I tryed without any success:

headers: {
    'content-type': "application/json ",
    'Access-Control-Allow-Origin': '*',
},

data: {
    ip: '123123',
    dhcp: true
},
withCredentials: true,
crossdomain: true,
proxy: {
    host: 'http://1.1.1.1',
    port: 1010
},
validateStatus: (status) => {
    return true; 
},

In the backend error on the last line::

json_data = request.get_json(force=True)
accountGuid = 'DummyAccount'
pdict = json_data[self.tableName]

Help me please. I don't understood what I have to do

OK I'm not sure what the logic is behind this but it recently happened to me. I had a put request that was giving me 500 internal server error but on postman the same request would work fine.

Here is what fixed the issue. axios has two ways of sending request.

axios.put(url,body,config);

and

axios(request object);

I am sharing my code. May be it helps you as well.

The request was failing at this code.

const { data } = await axios.put(`trainer-schedule/cancel-appointment-student/${id}`, null, {
        headers: {
            'Authorization': 'Bearer ' + await AsyncStorage.getItem('auth_token'),
            'Access-Control-Allow-Origin': '*',
        }
    });

I just changed it to other way and it started working.

const { data } = await axios({
        url: `trainer-schedule/cancel-appointment-student/${id}`,
        headers: {
            'Authorization': 'Bearer ' + await AsyncStorage.getItem('auth_token'),
            'Access-Control-Allow-Origin': '*',
        },
        method: 'put'
    });

My envoirenment is react-native, backend express js.

I would recommend to always test your requests on postman. It is the best tool out there to test apis. but what happened to me is a very rare case.

I hope it helps you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM