Search code examples
javascriptreactjspostaxiospostman

Set Params and Headers in axios post request


I recently encounter a stupid problem in my app width an axios request.

Here is the query:

const data =  { name: name }
const headers = { headers: { Authorization: `Bearer ${token}` } }

axios.post('http://localhost:3333/list/add', data, headers)

This request works but doesn't insert the name value...

When I console log the data variable I have the correct value and when I test this request on postman, it works perfectly.

Request on Postman

enter image description here

Request on my app

enter image description here

My API code:

async add({ request, auth, response }) {
        try {
            const list = new List()

            let user = await User.find(auth.current.user.id)
            let name = request.get('name')

            list.fill(name)

            const result = await list.save()

            await Database
                .insert({'user_id': user.id, 'list_id': list.id})
                .into('users_has_lists')
            
            return response.json({
                query_name: 'add',
                status: 'success',
                data: list
            })

        } catch (error) {
            return response.status(400).json({
                status: 'error',
                message: error.message
            })
        }
    }

Could someone tell me what is wrong with this request?


Solution

  • 2nd parameter in a post request count as body. To add params, you need to use another param. For your example, it should be

    axios.post('http://localhost:3333/list/add', null, {headers:headers, params:data})