When using vue-resource in a Vue application, the error "Uncaught TypeError: Cannot read property 'body' of undefined" sometimes occurs. This problem is usually because we use This is caused by the Content-Type of the request header not being correctly set in the POST or PUT request method of vue-resource. So, how do we solve this problem?
In vue-resource, it sets the request header by setting the header attribute. For example, if we want to set the Content-Type to application/json, then we can add the following code to the request configuration:
Vue.http.options.emulateJSON = true; Vue.http.options.headers = { 'Content-Type': 'application/json;charset=UTF-8' };
Among them, Vue.http.options.emulateJSON is to solve the problem that the browser will send options request during POST request, and Vue.http.options.headers is to set the Content-Type of the request header to application/json.
In addition, when using vue-resource to initiate a POST request, we need to perform a JSON.stringify operation on the data to convert the data into a JSON string before it can be correctly parsed by the server. The code is as follows:
var requestData = { name: 'test', age: 18 } Vue.http.post('/api/test', JSON.stringify(requestData)).then(function(response) { // 正常的请求返回结果 }).catch(function(response) { // 请求异常处理 });
In summary, if the "Uncaught TypeError: Cannot read property 'body' of undefined" error occurs when we use vue-resource in a Vue application, it is usually because the request header is not set correctly. Content-Type, we can make correct settings according to the above method and perform JSON string processing on the data to solve this problem.
The above is the detailed content of What should I do if 'Uncaught TypeError: Cannot read property 'body' of undefined' appears when using vue-resource in a Vue application?. For more information, please follow other related articles on the PHP Chinese website!