"Utilize Angular's $http options for requesting instead of using

When I attempt to send a $http POST request to a server API, the request method unexpectedly changes to OPTIONS. Strangely, this issue only occurs when working with localhost. To troubleshoot, I tried making the same request using Postman and it worked flawlessly.

Service:

function httpReg(userData) {
            console.log(userData)
            return $http({
                method: 'POST',
                url: CONFIG.APIHost + '/auth/signup',
                data: {
                    "username": userData.username,
                    "email":userData.email,
                    "password": userData.password
                },
                headers: {
                    'Content-Type': 'application/json; charset=utf-8'
                }
            });
        }

Screenshot: https://i.sstatic.net/Zx6ze.png
(source: joxi.net)

Answer №1

It seems that the preflight request has been rejected by your browser.

When the browser is unsure about the data source being accessed, it will first send a preflight request to the server. If this returns a status code of 200OK, then the original request will be sent by the browser.

This behavior is specific to browsers only, as other tools like Postman do not initiate preflight requests. Therefore, your code may work fine with them.

Here's how you can fix the issue:

  • Include headers for acceptable options such as GET, POST, OPTIONS, PUT in the requested resource.

Answer №2

It seems like there is a CORS issue at hand.

To resolve this, consider the following solutions:

  1. Attempt to set the referrer in your header
  2. You can try the following code snippet:

    app.config(['$httpProvider', function ($httpProvider) {
       //Reset headers to avoid OPTIONS request (aka preflight)
      $httpProvider.defaults.headers.common = {};
      $httpProvider.defaults.headers.post = {};
      $httpProvider.defaults.headers.put = {};
      $httpProvider.defaults.headers.patch = {};
    }]);
    
  3. Delete the x-auth* settings from the _app.js file within your yeoman/gulp settings.

For more information, please visit: AngularJS performs an OPTIONS HTTP request for a cross-origin 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

Tips for accessing raw POST data in PHP using $_SERVER

I am facing a challenge with my dynamic page where I use on-page filters that modify the data through AJAX response. My concern is how to access raw POST data when it's not visible in the URL... The link on my page appears as "example.com/default/lis ...

Submitting a form with JQuery and Ajax technology

I am encountering an issue where I need to submit a form within Ajax and I keep getting a 'form.submit is not a function' error in jQuery. $("#form").validate({ // Define validation rules rules: { type: "required", group ...

Guide on plotting latitude and longitude coordinates on Google Maps with Vue.js through JSON data fetched via AJAX

I have implemented a Vue.js script to fetch JSON data through an AJAX request. However, I am encountering issues with the code. <script> new Vue({ el: '#feed' , data: { details: [], }, mounted() { this.$nextTick(fu ...

Streamlining the process of implementing click events on elements selected by class using jQuery

Slowly but surely, I am gaining familiarity with jQuery and have reached the point where I desire to abstract my code. However, I am encountering issues when attempting to define click events during page load. Within the provided code snippet, my objectiv ...

The anchorEl state in Material UI Popper is having trouble updating

I am currently facing an issue with the Material UI popper as the anchorEl state remains stuck at null. Although Material UI provides an example using a functional component, I am working with a class-based component where the logic is quite similar. I w ...

Problems with Wordpress AJAX search functionality

I am currently working on implementing a search feature using AJAX to dynamically load posts. However, I am facing an issue where the results are not being displayed. This code snippet was adapted from another source and modified based on private feedback ...

How can we ensure that Ajax consistently provides useful and positive outcomes?

Here is my PHP code: function MailList() { $this->Form['email'] = $_POST["email"]; $index = $this->mgr->getMailList($_POST["email"]); } // SQL code function getMailList($email) { $mailArray = Array(); $sql ...

Generating a safe POST connection with express.js

Is there a simple method to generate a link for submitting a POST request using Express.js or a plugin? This approach can also be employed to enhance security for important actions like user deletion, including CSRF protection. In some PHP frameworks lik ...

The login process in Next-auth is currently halted on the /api/auth/providers endpoint when attempting to log in with the

My Next-auth logIn() function appears to be stuck endlessly on /api/auth/providers, as shown in this image. It seems that the async authorize(credentials) part is not being executed at all, as none of the console.log statements are working. /pages/api/au ...

Is it possible to create an animation in NextJS using framer-motion that triggers only during the initial page load and resets every 12 hours?

My website has a main page that loads in with an exciting framer-motion animation. I'm trying to figure out how to make sure this animation only plays the first time the page is loaded, and not every time the page is refreshed or navigated back to. Si ...

The choice between using inline style objects with React or utilizing traditional CSS classes presents distinct advantages and

Is there a discernible difference between utilizing an inline style object for react components and using a normal CSS class through the className attribute? Even when wanting to modify styles based on a specific event, simply changing the className should ...

Remove the active class after it has been clicked for the second time

Currently, I am working on a menu/submenu system where I want to toggle active classes when clicked. However, I encountered an issue - if the same menu item is clicked twice, I need to remove the active class. Initially, I tried using jQuery's toggleC ...

Unable to send image file and string via XHR is causing issues

This task may seem straightforward, but I've been struggling with it for hours. My goal is to upload an image file along with stringified coordinates to crop the image on the server-side. Below is my client-side code: var formdata = new FormD ...

Mastering the Art of Defining JavaScript Classes in React-Native

In my React Native project, I am faced with a situation where I need to create a new class: class customClass { email: string; name: string; constructor() { setUser(fbid: string, token: string): boolean { To keep things organized, I decide ...

Examine the angular scope for a particular occurrence

Exploring unit testing options using the Karma, Mocha, Chai, and CoffeeScript stack, I am aiming to verify if a variable is an angular scope. Although this code snippet does not function as expected: scope = $rootScope.$new() expect(scope).to.be.an.ins ...

What is the process of triggering an action from within getInitialProps?

I've been struggling to integrate Redux into a Next.js app, particularly when trying to use the dispatch function within getInitialProps. For some reason, the store keeps returning as undefined and I can't seem to pinpoint the issue. I've fo ...

The NodeJS HTTP server experiences server blocking due to pending requests

Trying to figure out a puzzling limitation I've encountered while experimenting. Here's the scenario: A user requests a route that takes approximately 10 seconds to calculate the output. Multiple concurrent requests may hit the same route at the ...

Using window.print as a direct jQuery callback is considered an illegal invocation

Curious about the behavior when using Chrome $(selector).click(window.print) results in an 'illegal invocation' error $(selector).click(function() { window.print(); }), on the other hand, works without any issues To see a demo, visit http://js ...

Using JavaScript to make an asynchronous call to the server via AJAX

Is it true that clients can block JavaScript in their browsers? If so, what impact does it have on AJAX calls - do they still function properly? ...

How to use jQuery to gather all the text from a textarea

Is there a way to automatically select all text inside a textarea when it is clicked on? Additionally, can this selection be deselected by clicking again? ...