在vue应用中使用vue-resource时,有时候会出现“uncaught typeerror: cannot read property 'body' of undefined”这个错误,这个问题通常是因为我们使用了vue-resource的post或put请求方法时没有正确地设置请求头的content-type导致的。那么,我们该如何解决这个问题呢?
在vue-resource中,它是通过设置header属性来设置请求头的,比如我们要设置content-type为application/json,那么我们可以在请求的配置中加入以下代码:
vue.http.options.emulatejson = true;vue.http.options.headers = { 'content-type': 'application/json;charset=utf-8'};
其中,vue.http.options.emulatejson是为了解决post请求时浏览器会发送options请求的问题,vue.http.options.headers是为了设置请求头的content-type为application/json。
另外,在使用vue-resource发起post请求的时候,我们需要对数据做一个json.stringify操作,将数据转为json字符串,然后才能正确的被服务器解析。代码如下:
var requestdata = { name: 'test', age: 18}vue.http.post('/api/test', json.stringify(requestdata)).then(function(response) { // 正常的请求返回结果}).catch(function(response) { // 请求异常处理});
综上,如果我们在vue应用中使用vue-resource时出现“uncaught typeerror: cannot read property 'body' of undefined”错误,一般是因为没有正确的设置请求头的content-type,我们可以根据以上方法进行正确的设置,并对数据进行json字符串处理,解决这个问题。
以上就是在vue应用中使用vue-resource时出现“uncaught typeerror: cannot read property 'body' of undefined”怎么办?的详细内容。