Search code examples
vue.jsvuejs2vue-resourcenuxt.js

vuejs FormData doesn't send json


I'm not quite sure what's causing it, but I'm using nuxtjs and attempting to send username and password to my Go server in json form. This is my vue code:

<template>
<div class="container">
  <h1>Login</h1>
   <div>
    <label for="username" >Username</label>
    <input class="input-block" type="text" v-model="username">
  </div>
  <div>
    <label for="password" >Password</label>
    <input class="input-block" type="password" v-model="password">
  </div>
  <div>
    <button v-on:click="login">Login</button>
  </div>
</div>
</template>

<script>
import Vue from 'vue'
import VueResource from 'vue-resource'
Vue.use(VueResource)

var loginURL = 'http://localhost:5000/login'

export default {
  data () {
    return {
      username: [],
      password: []
    }
  },
  methods: {
    login: function () {
      NProgress.start()
      var formData = new FormData()
      formData.append('username', this.username)
      formData.append('password', this.password)
      this.$http.post(loginURL, formData, {emulateJSON: true}).then(response => {
        console.log(response)
      }, response => {
        console.log(response)
      })
    }
  }
}
</script>

I have also tried to remove {emulateJSON: true} but the result is the same.

The server Go code looks like this:

func LoginPOST(w http.ResponseWriter, r *http.Request) {
  var loginForm struct {
    Username string `json:"username"`
    Password string `json:"password"`
  }
  body, err := ioutil.ReadAll(r.Body)
  if err != nil {
    // return 422
    return
  }
  fmt.Println("body string:", string(body))
  err = json.Unmarshal(body, &loginForm)
  if err != nil {
    fmt.Println(err)
    // return 422
    return
  }
  ...
}

The json.Unmarshal error will print: invalid character '-' in numeric literal, and that's because the r.Body is:

body string: -----------------------------10632500131211292840295750524
Content-Disposition: form-data; name="username"

MYUSERNAME
-----------------------------10632500131211292840295750524
Content-Disposition: form-data; name="password"

MYPASSWORD
-----------------------------10632500131211292840295750524--

I'm quite sure the Go code is correct, but I can't figure out why vue-resource sends the FormData in that way. I'd appreciate if someone could show how to send json and nothing else in the request


Solution

  • NProgress.start()
          var formData = {
            username: this.username,
            password: this.password
          }
          this.$http.post(loginURL, formData).then(response => {
            console.log(response)
          }, response => {
            console.log(response)
          })
    

    A regualr formdata object from the browser is never json encoded as far as i know. So just define a json object and everything should be fine.