Resolving the CORS preflight issue with Loopback API in Redux

My current setup involves a client application running on React-Redux and an API app on Loopback.

During local testing, I have the client app on port 8080 and the server app on port 3000.

While attempting to test Google OAuth (using the loopback-passport component) with the client app, I encountered the following error:

https://i.stack.imgur.com/QTO1C.png

However, when testing it using POSTMAN, everything works perfectly fine.

The client-side code is shown below:

require('babel-polyfill');
import { CALL_API } from 'redux-api-middleware'; 
import C from '../constants';
const API_ROOT = 'http://localhost:3000';

function googleLogin() {
    return async(dispatch) => {
        const actionResp = await dispatch({
            [CALL_API]: {
                endpoint: API_ROOT + '/auth/google',
                headers: {
                    'Access-Control-Allow-Credentials': 'false',
                    'Access-Control-Allow-Methods': 'GET',
                    'Access-Control-Allow-Origin': API_ROOT
                },
                method: 'GET',
                types: ['GET', 'GET_SUCCESS', 'GET_FAILED']
            }
        });

        if (actionResp.error) {
            console.log(actionResp);
            throw new Error('Some error in communication', actionResp);
        } else {
            console.log(actionResp);
        }   
    };
}

The CORS settings in the loopback middleware are as follows:

"cors": {
   "params": {
      "origin": true,
      "credentials": false,
      "maxAge": 86400
    }
  }

This issue seems straightforward, but any assistance would be appreciated.

Answer №1

Currently, most browsers do not have support for handling redirects in preflighted requests.

Here is a suggestion for your situation:

  1. Initiate a simple request to determine the eventual URL of the real preflighted request (by using Response.url with Fetch API or XHR.responseURL).
  2. Proceed to make the actual request using the obtained URL from step one.

Check out this link for more information on Cross-Origin Resource Sharing (CORS) and how it relates to preflighted requests and redirects.

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

Encountering difficulty inserting ajax response into a specific div element

What could be the issue? I've included the getElementById and I am receiving a response, as confirmed by Firebug. The response is correct, but for some reason it's not populating my div area. <script> $(document).ready(function () { $( ...

Automatically refreshing the page when the back button is clicked

Within my ASP.NET application, I have two pages - Page A and Page B. When a user clicks on a link on Page A, they are redirected to Page B. However, if the user then clicks the browser's back button while on Page B, I need to force a refresh of Page A ...

The jQuery prop("disabled") function is not operating as expected

Although I've seen this question answered multiple times, none of the suggested solutions seem to be working for my specific example. Hopefully, a fresh set of eyes can help me figure out what's going wrong. Even after adding alerts to confirm t ...

Remove a div element with Javascript when a button is clicked

I am working on a project where I need to dynamically add and remove divs from a webpage. These divs contain inner divs, and while the functionality to add new divs is working fine for me, I'm facing some issues with removing them. The code snippet b ...

Sending data from a bespoke server to components within NextJS

My custom server in NextJS is set up as outlined here for personalized routing. server.js: app.prepare() .then(() => { createServer((req, res) => { const parsedUrl = parse(req.url, true) const { pathname, query } = parsedUrl ...

Incorporate the block-input feature from sanity.io into your next.js blog for enhanced functionality

Currently, I'm in the process of creating a blog using next.js with sanity.io platform. However, I am facing some difficulties when it comes to utilizing the code-input plugin. What's working: I have successfully implemented the code component b ...

Encountering a rendering error with Jest while trying to load a functional child component

I encountered an error message stating Error: Uncaught [Error: Child(...): Nothing was returned from render while testing the Parent component. Below are the relevant files that were involved: /components/Page/Children/Child.js import React from "re ...

Add custom scripts to individual components within a Vue.js application

After extensive searching, I still can't seem to find a solution to my current issue. My focus is on a Vue project with vue-cli, where I need to inject various scripts into different pages (leveraging vue-router). Here are more specific details: Thi ...

Guide on efficiently inserting values into an array of objects

I'm looking to extract specific values from the enum below enum p { XDR = 1, PT1M = 2, PT1M_ = 2, PT5M = 3, PT5M_ = 3, PT15M = 4, PT15M_ = 4, PT1H = 5, PT1H_ = 5, P1D = 6, P1D_ = 6, P7D = 7, P1W = 7, ...

The React forwardRef Higher Order Component is failing to provide a reference to the container element

I'm currently working on creating a higher order component (HOC) for closing an element when clicked outside of its space, known as a generic close on outside solution. In my understanding, this can be achieved using forwardRef and HOC implementation ...

Issue with Component: Data is not being injected into controller from ui-router resolve, resulting in undefined data

Encountering an issue with resolve when using a component and ui-router: the data returned after resolving the promise is displaying as "undefined" in the controller. Service: class userService { constructor ($http, ConfigService, authService) { th ...

refresh the localstorage array using vanilla JavaScript

I am attempting to remove an element from an array stored in local storage. I am using vanilla JavaScript within a Vue.js 3 component. Here is my array: ["96", "281", "287", "415", "650", "661", & ...

Arrangement of images in an array

Here's the scenario I'm facing. https://i.stack.imgur.com/FbAfw.jpg So, I have an array of images that I want to use to create a gallery with a specific layout. I've tried using grid and playing around with :nth-child(even) and :nth-child( ...

What is the best way to display time instead of angles in highcharts?

Hey there! I'm currently working with highcharts and I have a polar chart where I want to display time on the y-axis instead of angles. Here's what I've tried so far: On the x-axis, I have angles and I've set tickInterval: 45,. How can ...

The functionality of the button is affected when it is placed on the same line as a h1 heading

My goal is to have the page title and profile button aligned on the same line in the header of each page. However, I've encountered an issue where the button doesn't function properly when placed on the same line but works fine when separated ont ...

Issue with updating input value during keyup event in Android Chrome specifically

Check out this straightforward jsfiddle: https://jsfiddle.net/gq9jga4q/33/ <input type="text" id="kbdhook" /> <div id="result" >1: </div> <div id="result2" >2: </div> <div id="result3" >3: </div> $('#kbdh ...

When using `npm publish`, any files located within the `node_modules

After developing an npm package, I included some modules in the node_modules directory to make them accessible as "modules". For instance, I have a module called my-module.js in node_modules which I require in my code using require('my-module'). ...

No content appearing on React screen

I initialized a fresh react project using "npx create-react-app name". After removing unnecessary files, the application no longer displays anything. I've encountered issues with react-router and defining routes as well. index.html: <!DOCTYPE html ...

Conceal a division on a webpage according to the URL of the specific

<script> function hideSearchField() { if (/menu/.test(window.location.href)) { document.getElementById('searchfield').style.display = 'none'; } } hideSearchField(); </script> I am trying to accomplish this using Jav ...

React: Issue with passing arguments to redux action hooks

In my React application, I have implemented Redux-Toolkit to manage reducers and actions with slices. I am currently working on creating actions that can update and delete values from the store, requiring arguments for their usage. To achieve this, I have ...