2017-09-13 95 views
-1

我試圖發送一個API請求到我們的API,但$ http.post不工作​​/返回一個無法讀取未定義錯誤的屬性'數據'。

有關如何做到這一點或解決方法的任何建議?或者如何正確調試問題?

代碼:

var data = { 
    from: "[email protected]", 
    to: "[email protected]", 
    content_type: "text/plain", 
    body: "Temp Message", 
    date: "2017-09-12T03:48:29.285Z", 
}; 

var config = { 
    headers : { 
     'Content-Type' : 'application/x-www-form-urlencoded; charset=utf-8', 
     'Authorization': 'Basic ' + "u/xx/yyy:zzz", 
    } 
} 

return $http.post('https://xxx/send', data, config) 
.success(function (data, status, header, config) { 
    console.log("SUCCESS"); 
}) 
.error(function (data, status, header, config) { 
    console.log("FAILED"); 
}); 

角/離子錯誤

0  330020 error TypeError: Cannot read property 'data' of undefined 
    at http://xxx.xxx.x.xxx:8101/lib/ionic/js/ionic.bundle.js:24536:24 
    at processQueue (http://xxx.xxx.x.xxx:8101/lib/ionic/js/ionic.bundle.js:29132:28) 
    at http://xxx.xxx.x.xxx:8101/lib/ionic/js/ionic.bundle.js:29148:27 
    at Scope.$eval (http://xxx.xxx.x.xxx:8101/lib/ionic/js/ionic.bundle.js:30400:28) 
    at Scope.$digest (http://xxx.xxx.x.xxx:8101/lib/ionic/js/ionic.bundle.js:30216:31) 
    at Scope.$apply (http://xxx.xxx.x.xxx:8101/lib/ionic/js/ionic.bundle.js:30508:24) 
    at done (http://xxx.xxx.x.xxx:8101/lib/ionic/js/ionic.bundle.js:24829:47) 
    at completeRequest (http://xxx.xxx.x.xxx:8101/lib/ionic/js/ionic.bundle.js:25027:7) 
    at XMLHttpRequest.requestError (http://xxx.xxx.x.xxx:8101/lib/ionic/js/ionic.bundle.js:24978:9) 
+1

它似乎你正試圖從任何未定義的對象的數據屬性,但代碼不是在這裏提供您的問題。 – Gaurav

回答

1

你的HTTP POST的Content-Type請求application/x-www-form-urlencoded。因此data應作爲參數格式序列化,例如使用$.param()

爲您的代碼,它看起來像:

... 
data = $.param(data); // using jQuery to serialze JSON as parameters. 
return $http.post('https://xxx/send', data, config) 
    .success(function (data, status, header, config) { 
     console.log("SUCCESS"); 
    }) 
    .error(function (data, status, header, config) { 
     console.log("FAILED"); 
    }); 

或者,如果服務器實際上接受JSON格式的Content-Type應改爲application/json。代碼看起來像這樣:

... 
var config = { 
    headers : { 
    'Content-Type' : 'application/json', 
    'Authorization': 'Basic ' + "u/xx/yyy:zzz", 
    } 
} 
... 
return $http.post('https://xxx/send', JSON.stringify(data), config) 
    ...