鍍金池/ 問答/HTML/ axios post怎么使用?傳大量數(shù)據(jù)時(shí),出現(xiàn)413 FULL head

axios post怎么使用?傳大量數(shù)據(jù)時(shí),出現(xiàn)413 FULL head

使用axios發(fā)布文章,代碼如下:

this.$axios({
    method: 'post',
    url: '/post',
    data: {
        description: opt.editorContent,
        time: time,
        ...
    },
})
.then(res => {
    ...
}

發(fā)送的請(qǐng)求是json格式的,后臺(tái)常規(guī)方式無法獲取,而且當(dāng)description數(shù)據(jù)過大會(huì)報(bào)413 FULL head錯(cuò)誤
手動(dòng)改Content-Type也不起作用

axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
回答
編輯回答
眼雜

哈哈,這個(gè)我剛用axios時(shí)也遇到過,jq的ajax是默認(rèn) application/x-www-form-urlencoded 的,也就是已經(jīng)加密過的,但是 axios 不是。

2018年2月19日 10:33
編輯回答
兮顏

感謝分享,學(xué)習(xí)了,倒是一直沒遇到過這個(gè)問題

2018年7月25日 06:43
編輯回答
孤毒

更新:
剛剛在sf看到一個(gè)終極解決方案

// http request 攔截器
axios.interceptors.request.use(
  config => {
    if (config.method === 'post' || config.method === 'put') {
      config.data = qs.stringify(config.data)
      // config.headers['Content-Type'] = 'application/x-www-form-urlencoded' 可以不配置,會(huì)自動(dòng)識(shí)別
    }
    return config
  },
  err => {
    return Promise.reject(err)
  })

==================

這個(gè)問題卡了一天了,百度谷歌都搜了一圈了,issue里也有一些信息(都使用了qs.stringify),但都使用了別名方式:

axios.post('http://something.com/', querystring.stringify({ foo: 'bar' }));

記錄下解決方法:
按道理,使用post方式,應(yīng)該使用['Content-Type'] = 'application/x-www-form-urlencoded'方式才對(duì)。。。為什么還是json類型的。
之前post一直是用params參數(shù)傳遞,導(dǎo)致和get請(qǐng)求一樣,變成了URL parameters跟在url里,導(dǎo)致了url太長(zhǎng),413 FULL head報(bào)錯(cuò)了
我喜歡使用配置的方式寫axios,此時(shí)post需要在transformRequest里處理了,才能識(shí)別為x-www-form-urlencoded類型

this.$axios({
    method: 'post',
    url: '/post',
    data: {
        description: opt.editorContent,
        time: time,
        ...
    },
    transformRequest: [function (data, headers) {
        console.log(headers)
        return qs.stringify(data)
    }],
})
.then(res => {
    ...
}
2018年6月1日 08:56