Issue with making requests across origins in Vuejs using axios

Currently, I am utilizing Vuejs and axios for handling web requests. So far, I have successfully managed to perform GET, POST, and PUT operations. However, the new challenge that I am facing is uploading media to the server. The server necessitates sending two-step requests in order to upload an image.

During the first step, I can acquire the upload URL link from the server within my promise and send the requisite headers. For the second step, all I need to do is use the obtained URL from step one and PUT the image file along with the same headers sent during the first step.

Unfortunately, I am encountering a Cross-Origin Request Blocked error and I am unsure of the root cause of this issue.

Below is the snippet of code:

 onPickFile() {
        var accessToken
        var self = this;

        firebase.auth().currentUser.getIdToken( /* forceRefresh */ true).then(function(idToken) {
            accessToken = idToken
            console.log("Id: " + self.id)
            console.log("Token : " + accessToken)
            var config = {
                headers: {
                    'Authorization': 'Bearer ' + accessToken,
                    'Content-Type': self.image.type,
                    'Media-Type': 'profile_image',
                    'x-goog-meta-media-type': 'profile_image',
                    'x-goog-meta-uid': self.id,
                }
            }
            console.log(config)

            axios.post('apilink', { // Step 1 - This step successfully returns the URL
                content_type: self.image.type
                }, config). // First step completed
            then(response => {
                console.log("Response URL is: " + response.data.upload_url)
                self.uploadUrlLink = response.data.upload_url

                console.log("Id: " + self.id)
                var config_2 = {
                    headers: {
                        'Authorization': 'Bearer ' + accessToken,
                        'Content-Type': self.image.type,
                        'Media-Type': 'profile_image',
                        'x-goog-meta-media-type': 'profile_image',
                        'x-goog-meta-uid': self.id,
                    }
                }
                console.log(config_2)
                axios.put(self.uploadUrlLink, self.image , config_2) // Step 2 - Issue with headers not showing up in "request headers"
                .then(response => { 
                    console.log("Response on PUT Image OK: " + response)
                })
                .catch(e => {
                    console.log("Error on PUT image: " + e)
                });

            })
            .catch(e => {
                console.log("Error on response on POST Image first step: " + e)
            });
        }).catch(function(error) {
            console.log("Error on getting token: " + error)
        });

    },

I am unable to view my headers under request headers:

Answer №1

When it comes to HTTP methods, using the OPTIONS method may not allow you to send data to the server. To overcome this issue, consider adding the OPTION method in the Access-Control-Allow-Methods header.

I trust this solution will be of assistance to you.

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

Instructions on implementing getJSON in this code

I recently set up a chained select box with JSON data to populate options, using this Fiddle. While the data is hardcoded for now, I am looking to load it using the $.getJSON() method. However, despite my efforts, I haven't been able to get the code r ...

Is there a specific requirement for importing a React component into a particular file?

I am facing an issue with my component and two JavaScript files: index.js and App.js. When I import the component into index.js, it displays correctly on the screen. However, when I import it into App.js, nothing appears on the screen. Here is the code fr ...

CORS blocking Axios POST request to Heroku causing a Network Error 503

Using the MERN Stack, everything was functioning correctly until modifications were made to the UI (such as relocating code to different components and altering styles). The issue lies with a specific POST request, while other requests that utilize Axio ...

The addition of the URL # fragment feature to Safari's browser caching system

Currently, I am focused on improving the speed of our website. To achieve this, the client is utilizing ajax to preload the expected next page of the application: $.ajax({url: '/some/real/path', ...}); Upon receiving a response from the server ...

The AJAX call returned undefined, leading to an error when trying to access the length property

I've scoured various resources to find a solution for this issue, but unfortunately, I haven't had any luck with implementing the code. The problem lies with my JSON parser function, which is designed to construct a table based on data received ...

Convert the string to a time format of hours and minutes (hh:mm)

I am currently working with an input field that requires a time value to be entered. The format for the Time field is in hh:mm on the 24-hour clock format, such as 7:30, 11:45, 16:10, 19:11, or 22:43. <input id="szReminderTime" type="text" value="" max ...

Convert a JSON array into a new format

Here is the JSON data input provided: "rows": [ [ 1, "GESTORE_PRATICHE", 1, "GESTORE PRATICHE", "canViewFolderManagement" ], [ 2, "ADM ...

npm not working to install packages from the package.json file in the project

When using my macbook air, I encounter an issue where I can only install npm packages globally with sudo. If I try to install a local package without the -g flag in a specific directory, it results in errors. npm ERR! Error: EACCES, open '/Users/mma ...

I'm having trouble sending registration emails through my server. What could be causing this issue?

Currently, I am in the process of developing a registration system that automatically sends an email with the user's username and password once they have successfully registered. The registration process functions smoothly up until the point where the ...

Error: Interface declaration for _.split is missing in the Lodash.d.ts file

For my current typescript project that heavily relies on Lodash with lodash.d.ts, I've encountered an issue with the _.split function not being implemented yet. It's listed under the 'Later' section in the .ts file. I need to find a wo ...

What is the best way to retrieve the JSON data from a POST request made through AJAX to a PHP file and save it in an array variable?

My ajax request sends JSON data to a PHP file named 'receive.php'. user_name , user_id, etc. are defined at the beginning of my script but can be changed to anything else. Below is the JavaScript code I am using: const data = { name: user_na ...

Exploring the life cycle of React.js components, how state behaves within them, and the asynchronous nature

There seems to be an issue with the expected data result and the actual data result. Even though the fetchData() and fetchnumberOfCommits() methods are being called from the componentWillMount(), the array is empty at first. However, the render method is b ...

React - The issue with my form lies in submitting blank data due to the declaration of variables 'e' and 'data' which are ultimately left unused

Currently, I'm working on incorporating a form using the react-hook-form library. Despite following the documentation and utilizing the handleSubmit function along with a custom Axios post for the onSubmit parameter like this: onSubmit={handleSubmit( ...

Is it possible to shorten properties and other definitions in Vue CLI along with minification for production?

While examining the output file (such as app.4a7888d9.js) generated by Vue CLI, I noticed that properties defined in the 'data' object, methods declared in the methods object, and Vuex state properties all retain their original names even after r ...

Having trouble parsing asynchronous script with cheerio parser

Utilizing cheerio for web crawling poses a challenge when encountering websites with asynchronous scripts. When attempting to extract all the scripts from such websites, they are often missed in the process. Here is an example of the code I am currently us ...

Creating JSON arrays with JavaScript and jQuery

User Information var Users=[{"Id":1,"FirstName":"John"},{"Id":2,"FirstName":"Emily"}] Call Information var CallInfo=[{"Id":1,"PercentageCalls":"22 %","TotalTime":"60:24 minutes","PercentageTime":"0 %","AvgTime":"0:22 minutes"},{"Id":2,"PercentageCa ...

Update settings when starting with chromedriver

I am currently using webdriver (), standalone selenium, and mocha for writing my test cases. These test cases are specifically designed for Chrome, so I rely on chromedriver for execution. However, when launching the browser, I need to ensure that the "to ...

Extract different properties from an object as needed

Consider the following function signature: export const readVariableProps = function(obj: Object, props: Array<string>) : any { // props => ['a','b','c'] return obj['a']['b']['c'] ...

Leverage Reveal.js within Next.js by installing it as an npm package

I am currently working on a project that requires integrating Reveal.js with Next.js. However, I am having trouble displaying the slides properly. Every time I try to display them, nothing shows up. Even after attempting to display some slides, I still en ...

Inadequate data being sent to the server from Angular2 post request

Currently, I have a form field whose value I am passing to a service as this.form.value. However, when I log this.form.value on the console, I see Object { email: "zxzx", password: "zxzxx" }. Despite this, when I send the same data to the service and make ...