Home>

I am currently creating an application using Nuxt.js and echo.
Data is saved without any problems when data is inserted into form-data with Postman.
If a Request is thrown from the front, an error occurs in the Bind part and it cannot be saved.
Below is the error message.
2019/11/26 00:01:05 sake_review_api.go: 27: action = Insert, err = code = 400, message = Request body can't be empty
I think that the cause is probably the front side because data can be saved from Postman,
Please let me know if you know the cause.
Thank you.

Here is the code.

The authentication part uses Firebase. When sending a request to the API, JWT is inserted into the header information and thrown.
The code on the front end side is as follows.

export default {
  components: {SakeReview, ReviewModal},
  data () {
    return {
      modal: false,
      title: '',
      review: '',
    }
  },
  methods: {
    async toggleReview () {
      await this. $store.dispatch ('toggleReview', {
        uri: ROUTES.POST.TOGGLE_REVIEW.replace (': id', this. $route.params.id),
        title: this.title,
        review: this.review,
      })
    },
export default ({$axios, app}) =>{
  $axios.onRequest (config =>{
    const token = app. $cookies.get ('jwt_token');
      if (token) {
        config.headers.common ['Authorization'] = `Bearer ${token}`
      }
  })
}
async toggleReview ({commit}, payload) {
    const client = createRequestClient (this. $axios)
    const res = await client.post (payload.uri, {
      "title": payload.title,
      "review": payload.review
    })
  },

On the API side, the UID is obtained from JWT, and if there is data with that UID, that data is obtained, and if there is data, a new User is created.
Bind the thrown request and process to save the data.

func Insert () echo.HandlerFunc {
    return func (c echo.Context) error {
        dbs: = c.Get ("dbs"). (* middlewares.DatabaseClient)
        token: = c.Get ("auth"). (* auth.Token)
        user: = models.User {}
        if dbs.DB.Table ("users"). Where (models.User {UID: token.UID}). First (&user) .RecordNotFound () {
            user = models.User {UID: token.UID}
            dbs.DB.Create (&user)
        }
        review: = new (models.review)
        if err: = c.Bind (review);err! = nil {
            log.Printf ("action = Insert, err =% s", err.Error ())
            return c.JSON (fasthttp.StatusInternalServerError, nil)
        }
        review.SakeIdentifyCode = c.Param ("id")
        review.UserID = user.ID
        res: = dbs.DB.Create (&review)
        if res.Error! = nil {
            log.Printf ("action = Insert, err =% s", res.Error)
            return c.JSON (fasthttp.StatusInternalServerError, nil)
        }
        return c.JSON (fasthttp.StatusOK, res.Value)
    }
}

Append

Request header information

2019/11/26 08:17:47 sake_review_api.go: 44: map [Accept: [application/json, text/plain, */*] Accept-Encoding: [gzip, deflate, br] Accept-Language: [ja-JP, ja;q = 0.9, en-US;q = 0.8, en;q = 0.7] Authorization: [Bearer eyJhbGciOiJSUzI1NiIsImtpkT4kFkK_Y9LGu2A] Connection: [keep-alive] Content-Length: [0] Origin : [http: // localhost: 3000] Referer: [http: // localhost: 3000/sake/P002604? sake_name =% E3% 80% 86&maker_name =% E4% BC% 8A% E6% 9D% B1% E9% 85 % 92% E9% 80% A0] Sec-Fetch-Mode: [cors] Sec-Fetch-Site: [same-site] User-Agent: [Mozilla/5.0 (Macintosh;Intel Mac OS X 10_15_0) AppleWebKit/537.36 ( KHTML, like Gecko) Chrome/78.0.3904.108 Safari/537.36]] `
_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.108 Safari/537.36]]
  • Answer # 1

    Before correction

    request-client.js

    export class RequestClient {
      constructor (axios) {
        this.axios = axios
      }
      async get (uri, params = {}) {
        const queryString = Object.keys (params) .map (key =>key + '=' + params [key]). join ('&');
        const query = queryString.length>0? `${uri}? ${queryString}`: uri
        return await this.axios. $get (query)
      }
      async post (uri) {
        return await this.axios. $post (uri, data)
      }
    }
    export function createRequestClient (axios) {
      return new RequestClient (axios)
    }


    ↓↓↓↓↓↓

    After correction
    async post (uri, data = {}) {
      return await this.axios. $post (uri, data)
    }