When sending an Axios POST request, a "Network Error" message may be received even when the status code is 200 and there is a valid response

Currently, I am utilizing Vue JS version 2.5 along with Axios:

"vue": "^2.5.17",
"vue-axios": "^2.1.4",
"axios": "^0.18.0",

The main issue I am facing involves making a POST call like so:

const data = querystring.stringify({
                'email': email,
                'password': password,
                'crossDomain': true, // this is optional and added by me for testing purposes
            });

var axiosConfig = {
                    headers: {
                        'Content-Type': 'application/x-www-form-urlencoded',
                        // "Access-Control-Allow-Origin": "*",
                        'Accept': '*',
                    }
                };

axios.post(url, data, axiosConfig)
                .then((response) => {
                    console.log('response');
                    console.log(response);
                })
                .catch((error) => {
                    console.log('error');
                    console.log(error);
                });

I have also attempted the call without the "axiosConfig" parameter. However, it consistently falls into the catch block with the message: Error: Network Error

In the Network tab of the browser, a 200 status code is displayed alongside a proper Response (featuring valid JSON). Although it appears to function correctly, Axios presents an error and no response.

A warning in the console reads:

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://url/api/page. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing).

When attempting the same call through Postman, it performs successfully. The distinction lies in Axios sending the headers "Origin" and "Referrer" with my localhost:8080, which differs from the API URL being called.

Is there a way to execute this call from Axios without encountering this error? Thank you.

UPDATE

This operation functions as intended when using PHP:

$curl = curl_init();

        curl_setopt_array($curl, array(
            CURLOPT_URL => "https://myurl",
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_ENCODING => "",
            CURLOPT_MAXREDIRS => 10,
            CURLOPT_TIMEOUT => 30,
            CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
            CURLOPT_CUSTOMREQUEST => "POST",
            CURLOPT_POSTFIELDS => "------WebKitFormBoundaryTrZu0gW\r\nContent-Disposition: form-data; name=\"email\"\r\n\r\nemail\r\n------WebKitFormBoundaryTrZu0gW\r\nContent-Disposition: form-data; name=\"password\"\r\n\r\npassword\r\n------WebKitFormBoundaryTrZu0gW--",
            CURLOPT_HTTPHEADER => array(
                "Postman-Token: 62ad07e5",
                "cache-control: no-cache",
                "content-type: multipart/form-data; boundary=----WebKitFormBoundaryTrZu0gW",
                "email: email",
                "password: password"
            ),
        ));

        $response = curl_exec($curl);
        $err = curl_error($curl);

        curl_close($curl);

        if ($err) {
            echo "cURL Error #:" . $err;
        } else {
            echo $response;
        }

I merely copied the Postman-generated call and tested it on a different page, where it performed flawlessly. Hence, the issue pertains not to CORS but rather to my Javascript implementation.

Answer №1

To resolve the issue, make sure CORS is enabled on your API. What specific programming language or framework are you currently working with?

For further guidance, you can check out this resource:

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

The combination of Three.js and React

Hello everyone! I am completely new to Three.js and I'm currently attempting to integrate it with React. While looking for resources, I came across this helpful medium article on the topic: Starting with React 16 and Three.js in 5 minutes My goal is ...

Using Javascript to save content to a text file across multiple lines

I am working on a coding project that involves extracting data from a JSON file via a URL and parsing the JSON content. The script successfully filters out the necessary data, but now I want to write this data to a text file with each piece of information ...

Updating a div using PHP elements

Currently, I'm using a webcam to capture images for a project related to learning. My goal is to showcase the recently taken photos. After taking a photo, it gets stored in a folder. To display all the collected photos within a <div>, I need to ...

retrieve the variable contained within the callback function

const axios = require('axios'); const options = { url: 'https://api.github.com/repos/axios/axios', headers: { 'User-Agent': 'axios' } }; function handleResponse(error, response, body) { if (!error && re ...

Getting the values of $scope variables from AngularJS in the controller to the view

I have a simple scope variable on my AngularJS Controller. It is assigned a specific endpoint value like this: $scope.isItAvailable = endpoint.IS_IT_AVAILABLE; How can I properly use it in my view (HTML) to conditionally show or hide an element using ng- ...

Tips for ensuring that the horizontal scroll bar remains consistently positioned at the bottom of the screen

There are two div sections on a page, with one positioned on the left and the other on the right. The div on the right contains multiple dynamically generated tags which necessitate a horizontal scroll bar (overflow:auto). This causes the div's height ...

Incorporating Card Layouts with SwiperJS

Reference Code: See Example on Code Sandbox I am looking to implement a swiper that allows for navigating one slide at a time with a layout where slidesPerView: "auto" and fixed width are used. The first two slides behave as expected, but the la ...

Maintain parental visibility with children when navigating to a different page

I am currently working on a vertical accordion menu that opens on hover, stays open, and closes when other items are hovered. The great assistance I received from @JDandChips has been instrumental in getting this feature up and running. Now, my main focus ...

Challenges with xmlHttpRequest in a search autocomplete feature similar to Google's suggestion feature

I am currently working on implementing an autosuggestion search field that functions similarly to Google Suggestion. I am utilizing pure JavaScript/AJAX along with two files: index.php and ajax-submit.php (which is responsible for querying the database). H ...

Modification of a CSS element

The CSS I am working with looks like this: .cls .imageX { float:left; } .cls .imageY { float:right; } It is currently being used on a page in this way: <div class="cls"> <a href="" class="imageX"><img src="left.png"/></a> &l ...

How do I extract a parameter when passing it to a promise in NodeJS?

Let me simplify this query. I need to fetch a parameter used in a promise. Here's the gist of the code: function foo(param) { return fromPromise(blabla, blabla2, param) .then((res) => { return res }).catch((error) => { console.log( ...

How to Incorporate an Anchor Link into a Div as well as its Pseudo Element using CSS, Javascript, or jQuery

How can I make both the menu item and its icon clickable as a link? When either is clicked, the link should work. Here is a CodePen example: http://codepen.io/emilychews/pen/wJrqaR The red square serves as the container for the icon that will be used. ...

Could you explain the purpose of the app.use(cors()) function call?

I'm aware that accessing an API with a different domain than our own is not allowed. Nonetheless, I often observe individuals incorporating the cors module into their Express.js applications in order to interact with APIs and then utilizing it in this ...

Is there a "Read more" link to expand the content on the page?

I am struggling to figure out why my JavaScript code for toggling between showing more text and less text is not functioning correctly. My goal is for the user to click on the "Show More" button to reveal additional text, and then be able to click on "Show ...

Exploring the Differences in CSS Styling between Web and Mobile Platforms

Recently, I launched my new website and encountered a peculiar issue. Upon clicking on Pickup Date & Time, a bootstrap datepicker pops up like it should. However, the problem arises when viewing the website on mobile devices - the datepicker appears offsc ...

How can Javascript be used to interact with buttons and select options?

Can anyone help me with creating a JavaScript code that can select an option from a drop down, click on that option, and then add it to the cart by clicking another button? So far, I have attempted the following: browser.getelementbyid("id").invokemembe ...

5-item carousel in CSS gridView

I'm currently working on a thumbnail slider project. My goal is to display 5 thumbnails at a time, and allow users to move to the next or previous set of thumbnails by clicking on the corresponding buttons. I attempted to modify an existing slider tha ...

Using Three.js to apply multiple images onto a sphere and have individual control over each one

I have a 3D sphere that I am looking to map an array of images onto. I want to be able to control each image independently, allowing for fading in and out of each image. To better illustrate my goal, I will provide an example image of what I am trying to a ...

What does the phrase "sill package range manifest" signify?

Every time I execute the command npm install, a line of fetchMetadata: sill pacote range manifest for <pacakge name> appears. Could you explain what 'sill', 'pacote', 'range', and 'manifest' mean in this contex ...

Dealing with errors when implementing an Angular 2 route guard that returns an Observable of type boolean can be a

My route guard is implemented as follows: @Injectable() export class AuthGuard implements CanActivate { constructor(private router: Router, private authenticationSvc: AuthenticationService) { } canActivate(): Observable<boolean> { return this. ...