我試圖使用我的Angular控制器將圖像上傳到Cloudinary。請求是未簽名的,我沒有使用任何庫。它只是一個簡單的POST請求,,當我在一個靜態HTML頁面上使用jQuery嘗試它時就起作用了。來源http://localhost.com:8000不允許通過Access-Control-Allow-Origin嘗試使用AngularJS將圖像上傳到Cloudinary
無論如何,這是我的控制器:
myapp.controller('DashboardController', ['$scope', '$http', function($scope, $http) {
$scope.uploadPicture = function() {
var formData = new FormData();
var file = document.getElementById("file").files[0];
formData.append("file", file);
formData.append("upload_preset", "[MY UNSIGNED UPLOAD PRESET]");
$http({
method: 'POST',
url: 'https://api.cloudinary.com/v1_1/[MY CLOUD NAME]/image/upload',
data: formData,
}).then(function successCallback(response) {
alert(respose.secure_url);
}, function errorCallback(response) {
console.log(response);
alert(response);
});
};
}]);
我得到的錯誤是:
XMLHttpRequest cannot load https://api.cloudinary.com/v1_1/[MY CLOUD NAME]/image/upload. Origin http://localhost.com:8000 is not allowed by Access-Control-Allow-Origin.
爲什麼會出現這個錯誤?請任何幫助。爲了重複我之前說過的話,用jQuery編寫的確切代碼在名爲index.html的靜態頁面上完美工作,所以我對這個問題感到迷茫。
這是jQuery代碼:
(function() {
$('#uploadBtn').click(function() {
var formData = new FormData();
var file = document.getElementById("file").files[0];
console.log(file);
formData.append("file", file);
formData.append("upload_preset", "[MY UNSIGNED UPLOAD PRESET]");
$.ajax({
url: "https://api.cloudinary.com/v1_1/[MY CLOUD NAME]/image/upload",
type: 'post',
data: formData,
contentType: false,
processData: false,
success: function(response){
alert(response.secure_url);
},
error: function(jqXhr, textStatus, errorThrown){
console.log(errorThrown);
}
});
});
})();
和
<input type="file" id="file"/>
<button id="uploadBtn">Upload</button>
上述所有在叫index.html
靜態HTML文件。
看起來像服務器端錯誤..是否啓用CORS? –
@suraj我相信是的,因爲正如我之前所說,這與靜態html頁面一起工作。 –
*「當我在一個靜態的html頁面上使用jQuery來測試它時工作」*顯示代碼。另外,當你這樣做時,包含該jQuery代碼的**精確**源代碼頁面URL是什麼? –