简体   繁体   中英

axios in vue js send request as string , not object

how can i resolve this problem ? this is main.js I want to send the name to the server via axios in vuejs But I can't get name from $_Request

import Vue from 'vue'
import App from './App.vue'
import axios from 'axios'

Vue.config.productionTip = false
Vue.prototype.$http = axios

new Vue({
  render: h => h(App),
}).$mount('#app')

and this is my template script

export default {

  data() {
    return {
    header:{headers: {
      'Content-Type': 'application/x-www-form-urlencoded',
    }},
      name:null,
      r:null,
    }

  },
  methods: {
    post:function(){
      this.$http.post('http://127.0.0.1/saver.php',{
          name:this.name,
        },this.header).then(r => {
       this.r=r;
       // eslint-disable-next-line no-console
       console.log(typeof {name:this.name})
      }).catch(err => {
   // eslint-disable-next-line no-console
   console.log(err.response.data)
});
    }
  },
}
</script>

and this is my php server side code :

<?php
header('Access-Control-Allow-Origin: *');
header('Content-Type: application/json');
if ($_SERVER['REQUEST_METHOD'] == 'POST' && !empty($_REQUEST))
{

    print_r($_REQUEST);
}
?>

params :

参数

and this is response that returned from server :

响应服务器

As Axios documentation states,

By default, axios serializes JavaScript objects to JSON. To send data in the application/x-www-form-urlencoded format instead, you can use one of the following options.

<...>

In a browser, you can use the URLSearchParams API

<...>

Alternatively, you can encode data using the qs library

It should be:

this.$http.post('http://127.0.0.1/saver.php', qs.stringify({
  name:this.name,
}),this.header)

Alternatively, server side can be modified to use JSON payload exclusively.

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