The request to upload an image to Cloudinary using AngularJS is being blocked due to the origin http://localhost.com:8000 not being allowed by Access-Control-Allow-Origin

I've been attempting to upload images to Cloudinary through my Angular controller without using any libraries. The POST requests are unsigned, and interestingly, I was successful when I tested it with jQuery on a static HTML page.

Here is the code snippet from my controller:

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);
        });
    };

}]);

I encountered this error message:

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.

What could be causing this error? Your assistance would be greatly appreciated. As mentioned before, the exact functionality implemented in jQuery worked flawlessly on a static HTML page named index.html, so I'm puzzled by this issue.

This is the working jQuery code:

(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 );
                }
            });
        });
    })();

and

<input type="file" id="file"/>
<button id="uploadBtn">Upload</button>

All of the above code snippets were included in a static HTML file called index.html.

Answer №1

It seems like you are using a different browser from Chrome and accessing your "static HTML" page directly from the file system instead of through a web server process, for example, by using a file:// URL rather than an http:// URL (like http://localhost:8000 in your Angular example).

Various browsers handle file:// URLs differently. Chrome, for instance, considers no cross-origin calls valid with a file:// URL (and may even treat other file:// URLs as different origins), while some other browsers exempt file:// URLs from the Same Origin Policy entirely, allowing them to access external content.

So the issue isn't really about Angular versus jQuery, it's about using a file:// URL versus an http:// URL. All http:// (and https://) URLs are subject to the Same Origin Policy across all browsers.

If I'm understanding correctly, the problem might be that the service you're trying to interact with does not permit requests originating from localhost:8000.

Answer №2

Give this a shot,

$httpProvider.defaults.withCredentials = true;
$httpProvider.defaults.useXDomain = true;
$httpProvider.defaults.headers.common['Access-Control-Allow-Origin'] = "*";
$httpProvider.defaults.headers.common['Access-Control-Allow-Methods'] = "POST, GET, OPTIONS, PUT, PATCH";
$httpProvider.defaults.headers.common['Access-Control-Allow-Headers'] = "Origin, Content-Type, Accept, Authorization";

I encountered a similar issue when running my application locally and was able to resolve it by including these headers.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best way to navigate a dynamic table in Vue.js?

I'm currently working on creating dynamic tables in Vue using loops where users can upload a table and view it. <el-table :data="filtered" border style="width: 100%" height="500" @selection-change="handleSelectio ...

Location of chat icon in Dialogflow messenger

After successfully embedding the Dialogflow messenger in my website, I noticed that in mobile view, the chat icon is blocking the bottom navigation bar. You can refer to the screenshot here. Is there a way to reposition the chat icon higher on the page? I ...

What is the procedure for defining the secret code for a private key in saml2-js?

I need to implement a key/cert with a passphrase in my project that's currently using saml2-js. I have already set up everything but encountering a bad decrypt error without the passphrase. Is there a way to incorporate this passphrase? Below are the ...

Incorporate information into a React component

I'm currently working on my initial react component and facing a challenge while adding items to the parent element through an external click event. The user needs to select from a list of search results, and I intend for these selections to be incorp ...

Adjust the z-Index of the list item element

I am attempting to create an effect where, upon clicking an icon, its background (width and height) expands to 100% of the page. However, I am struggling with ensuring that the 'effect' goes underneath the this.element and above everything else. ...

Switch to a different element by rolling over one

I need assistance with a menu setup where the submenus are located in separate divs on the page. Both the parent elements and submenus have numerical identifying IDs, and I am struggling to create a rollover effect that would automatically open the corresp ...

Guide to uploading a PDF to Google Drive and embedding it on an HTML static website

I manage a static HTML site for a small food shop. They require monthly menu uploads in PDF format. I believe uploading to Google Drive would be a more efficient solution than creating a separate admin view for file uploads. Can anyone advise me on how to ...

Node: How can I retrieve the value of a JSON key that contains a filename with a dot in

I have a JSON file named myjson.json, with the following structure: { "main.css": "main-4zgjrhtr.css", "main.js": "main-76gfhdgsj.js" "normalkey" : "somevalue" } The purpose is to link revision builds to their original filenames. Now I need to acce ...

The Next.js 404 error page seems to be malfunctioning. Any ideas on what might be causing this issue?

Whenever I attempt to access a non-existent route, the home page loads without changing the URL. My expectation was to see a 404 error page. To handle this issue, I created a custom error page called pages/_error.js import Page404 from './404'; ...

sharing AMD modules between multiple files

As of now, I am in the process of constructing the Ember.SimpleAuth library - a tool designed for facilitating authentication and authorization within Ember.js applications (https://github.com/simplabs/ember-simple-auth/tree/sub-packages). This library pro ...

Creating Typescript types based on the values of other props: A guide

Can the TypeScript prop type be dynamically changed based on the runtime value of another prop? For instance type MyComponent = { propA: boolean | string propB: typeof propA boolean ? number : string } Is it feasible to determine the prop type of p ...

Generating references dynamically without the use of strings

UPDATE: Our current React version is 16.2.0, which is important for this question (check out this answer). From what I understand, this is the recommended way to create a ref in our React version: <div ref={(r) => { this.theRef = r; }}>Hello!< ...

The error message "POST .../wp-admin/admin-ajax.php net::ERR_CONNECTION_CLOSED" appears when a WordPress AJAX request receives data that exceeds 1MB in size

When I attempt to submit a jquery ajax form from the frontend and upload a blob (a variable of string) as a .txt file to WordPress using wp_handle_upload(), everything works smoothly until the file size reaches around 1mb. At that point, an error is displa ...

Using jQuery to create clickable images by enclosing them in an `<a>` tag

How can I make each image with a specific class clickable? I would like jQuery to: Retrieve the src attribute of the image. Enclose the image within an a href tag that includes that src URL. .clickable { padding: 20px; border: 1px ...

Is it possible to execute in a specific context using npm?

I am seeking to execute npm scripts that are executable by VuePress. For instance, I have VuePress installed and would like to run the command vuepress eject. Although I can access vuepress in my scripts, there is no specific script for eject: "scr ...

Experience a seamless transition to the next section with just one scroll, allowing for a full

I've been attempting to create a smooth scroll effect to move to the next section using Javascript. However, I'm encountering issues with the window's top distance not being calculated correctly. I'm looking to have the full screen div ...

What is the best way to display SVGs from an API response using next/image or the <img> tag in Next.js?

I have a collection of SVGs being returned from an API response, which I am fetching inside the useEffect. The response structure is as follows: {svg1: 'https://remoteserver.com/assests/svg1.svg', ...and so on} (These SVGs are not static assets ...

Unable to navigate a simulated scrollbar

As someone who is new to web development, I am embarking on the journey of building a UI Grid that can effectively display a large amount of data. My goal is to implement a scrollbar that allows for horizontal scrolling across approximately 1,000,000 data ...

What is causing the TypeError when trying to set a property on undefined in AngularJS?

I've taken on the challenge of building a microblog app to learn more about angularJS. One thing that's really getting me is trying to understand the differences between service, factory, and provider. After some research, I decided to go with s ...

Converting lists to JSON format in a C# web form

Utilizing JSON.stringify, I have implemented textbox autocomplete for a web-form that suggests city names based on user input. The goal is to retrieve relevant city names from the database and display them as suggestions in the autocomplete feature after t ...