Angular $ http错误响应statusText始终未定义
我试图向用户返回一个自定义错误消息,让他们知道出现错误时出了什么问题,但我已经尝试了所有内容来显示消息,似乎没有任何东西正在捕获它。 这是我的角度代码:
$scope.save = function (style) { styleAPIservice.addStyle(style).success(function () { $scope.success = "Style added successfully"; }).error(function (data, status, headers, config, statusText) { $scope.error = "An error occurred while saving style: " + data + "|"+data.data+"|"+data.statusText+"|"+statusText; }); }
这是它调用的styleAPIservice函数:
styleAPI.addStyle = function (style) { return $http.post(AppRoot + "api/StyleAPI/", JSON.stringify(style), { headers: { 'Content-Type': 'application/json' } }); }
这是API函数:
[HttpPost] public HttpResponseMessage PostStyle(Style style) { if (string.IsNullOrEmpty(style.Pattern.PatternName) || string.IsNullOrEmpty(style.StockNumber)) return Request.CreateErrorResponse(HttpStatusCode.BadRequest, "Pattern Name and Stock Number are required."); var checkStyle = StyleRepository.LoadStyleByStockNumber(style.StockNumber); if (checkStyle != null) return Request.CreateErrorResponse(HttpStatusCode.BadRequest, "Style number already exists. Please use update."); try { // Save style } catch (Exception ex) { return Request.CreateErrorResponse(HttpStatusCode.BadRequest, "Error creating style: " + ex.Message); } HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.Created, style); response.Headers.Location = new Uri(Url.Link("DefaultApi", new { id = style.StyleId })); return response; }
以下是发生错误时返回的内容(例如Style已存在):
An error occurred while saving style: [object Object]|undefined|undefined|undefined
我究竟做错了什么? 我觉得我到处搜索并尝试了所有可能的建议,但我不知道为什么我无法显示我的错误消息。
用.catch()替换.error()。
$http.post('/url',json) .success(function(data, status, headers, config){ // some code here }) .catch(function(data, status, headers, config){ // <--- catch instead error data.statusText; //contains the error message });
对于可能遇到此问题的任何其他人,该消息都在data.Message
。 我通过调试JS找到了它。
StatusText只能通过使用来自$ http的.then,而不是来自.Post帮助器方法而不是来自.success .error。
function handleSuccess(data, status, headers, config, statusText){ //some function of your own invention } function handleError(data, status, headers, config, statusText){ //some function of your own invention } //borrowed from angularJs Http module function headersGetter(headers) { var headersObj = isObject(headers) ? headers : undefined; return function(name) { if (!headersObj) headersObj = parseHeaders(headers); if (name) { var value = headersObj[lowercase(name)]; if (value === void 0) { value = null; } return value; } return headersObj; }; } //borrowed from angularJs Http module function isSuccess(status) { var istatus = Math.max(status, 0); return 200 <= istatus && istatus < 300; } $scope.postMyData = function ($http) { var req = { method: 'POST', url: 'destinationURL.html', headers: { 'Content-Type': 'application/json' }, data: $scope, }; // example response from : //http://plnkr.co/edit/atRTBQC62YdZzKH8mWqu?p=preview //{ // "data":"Hello, $http!", // "status":200, // "config":{ // "method":"GET", // "transformRequest":[null], // "transformResponse":[null], // "url":"http-hello.html", // "cache":{}, // "headers":{"Accept":"application/json, text/plain, */*"} // }, // "statusText":"OK"} $http(req). then(function (response) { var data = response.data; var status = response.status; var headers = headersGetter(headers) var config = response.config; var statusText = response.statusText; scope.messageToUsers = (isSuccess(response.status)) ? handleSuccess(data, status, headers, config, statusText) : handleError(data, status, headers, config, statusText); }) }
- 使用angular post将两个参数传递给WEB API调用
- 是否可以在ASP.NET Web API和SPA中使用基于cookie的身份validation?
- HttpContext.Current.Items 无效,因为AngularJS调用创建新会话
- Web Api 2 – 如何从HTTPGET返回映像(来自Azure存储的MemoryStream)而不保存到磁盘?
- Angular路由模板URL是否支持ASP.Net MVC 5项目中的* .cshtml文件?
- CORS:凭证模式是’包含’
- POST请求标头中的content-type缺少FormData边界
- web api put识别查询字符串但不识别正文
- AngularJs和ASP.NET MVC 5-ng-model覆盖文本框值