Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

posting data with Axios

I need to use a code like this:

vr1 = 'firstName'
value1 = 'Fred'
vr2 = 'lastName'
value2 = 'Flinstone'

axios({
  method: 'post',
  url: '/user/12345',
  data: {
     vr1: Value1,
     vr2: Value2
  }
});

so, it will be the same as executing:

axios({
  method: 'post',
  url: '/user/12345',
  data: {
    firstName: 'Fred',
    lastName: 'Flintstone'
  }
});

Is this possible using Java Script 6?

like image 662
Jose Cabrera Zuniga Avatar asked Apr 18 '17 23:04

Jose Cabrera Zuniga


People also ask

How do I post data on Axios post?

A POST request can be made using Axios to “post” data to an endpoint. This endpoint may then use this POST request to perform a certain task or trigger an event. The HTTP post request is performed by calling axios. post() .

How does Axios post work?

A POST request is created with post method. Axios automatically serializes JavaScript objects to JSON when passed to the post function as the second parameter; we do not need to serialize POST bodies to JSON.

How pass JSON data in Axios POST request?

To post request with JSON data with Axios, we call axios. post with the JSON payload as the 2nd argument. const dt = { data: { value: "abc" } }; const request = axios. post(url, dt);


1 Answers

Try this one also and replace

baseURL
with your own hostname url
import axios from 'axios'

let var1 = 'firstName'
let value1 = 'Fred'
let var2 = 'lastName'
let value2 = 'Flinstone'

const api = axios.create({baseURL: 'http://example.com'})
api.post('/user/12345', {
    var1: value1,
    var2: value2
})
.then(res => {
     console.log(res)
})
.catch(error => {
     console.log(error)
})
like image 187
Njeru Cyrus Avatar answered Sep 29 '22 17:09

Njeru Cyrus