简体   繁体   中英

Posting form data with Vue frontend with Axios to Express backend

I have a basic bootstrap-vue form and I'm trying to post the form-data with Axios to Express.

Yet, at the moment my req.body response looks like this: body: { '{"name":"","country":"","message":""}': '' }

I would really really appreciate help how I could fix this issue. I can't seem to figure this one out.

Form:

<b-form @submit="onSubmit">
<b-form-input v-model="form.name" required></b-form-input>
<b-form-input v-model="form.country" required></b-form-input>
<b-form-input v-model="form.message" required></b-form-input>

Method:

  methods: {
    onSubmit (evt) {
      evt.preventDefault()
      axios.postForm(this.form)
    }
  }

Axios:

const AXIOS = axios.create({
    baseURL: 'http://localhost:8081', // I'm running my node server here
    timeout: 5000,
    headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
});

export default {
    postForm (form) {
        return AXIOS.post(`/newmessage/`, form)
    }
};

Express:

// ..require stuff here

app.use(bodyParser.urlencoded({ extended: true }));

app.post('/newmessage/', (req, res) => {
    console.log(req.body)
});

This was fix:

Method:

  methods: {
    onSubmit (evt) {
      evt.preventDefault()
      axios.postForm(JSON.stringify(this.form))
    }
  }

Axios:

const AXIOS = axios.create({
    baseURL: 'http://localhost:8081',
    timeout: 5000,
    headers: { 'Content-Type': 'application/json' }
});

Express:

app.use(bodyParser.json());

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