Cross-origin resource sharing (CORS) restricts changes in GraphQL Yoga

I'm currently working on a project that involves a backend using graphql prisma and a frontend with a graphql yoga express server. I've encountered an issue where I am unable to call a signout mutation due to the CORS policy blocking it. Despite adding cors settings to my graphql yoga server, the error persists. While GraphQL Queries work seamlessly, Mutations are restricted. The URL for my frontend is 'http://localhost:7777' and the yoga server is accessible at 'http://localhost:4444/'. Here's the specific error message:

Access to fetch at 'http://localhost:4444/' from origin 'http://localhost:7777' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

[Network error]: TypeError: Failed to fetch

Cors Configuration in GraphQL Yoga Server:

server.start(
{
    cors: {
        credentials: true,
        origin: [process.env.FRONTEND_URL],
    },
},
deets => {
    console.log(
        `Server is now running on port http://localhost:${deets.port}`
    );
}
);

Mutation:

// import React, { Component } from 'react';
import { Mutation } from 'react-apollo';
import styled from 'styled-components';
import gql from 'graphql-tag';
import { CURRENT_USER_QUERY } from './User';
import { log } from 'util';

const SIGN_OUT_MUTATION = gql`
mutation SIGN_OUT_MUTATION {
    signout {
        message
    }
}
`;

const SignOutBtn = styled.button`
color: ${props => props.theme.textMedium};
padding: 10px;
margin-right: 20px;
text-align: center;
font-family: garamond-light;
border: 1px solid ${props => props.theme.textMedium};
border-radius: 5px;
transition: background-color 0.5s ease;
transition: color 0.5s ease;
:hover {
    background: ${props => props.theme.textMedium};
    color: ${props => props.theme.white};
}
`;

const Signout = props => (
<Mutation
    mutation={SIGN_OUT_MUTATION}
    refetchQueries={[{ query: CURRENT_USER_QUERY }]}
>
    {signout => (
        <SignOutBtn
            onClick={() => {
                console.log("comes here")
                signout();
            }}
        >
            Sign Out
        </SignOutBtn>
    )}
</Mutation>
);
export default Signout;

I would appreciate any insights on what could be causing this issue. Thank you!

Answer №1

To overcome the issue, a middleware was implemented to configure the response headers appropriately, preventing the fetch operation from failing.

server.express.use(function(req, res, next) {
  res.header('Access-Control-Allow-Origin', 'http://localhost:7777');
  res.header(
    'Access-Control-Allow-Headers',
    'Origin, X-Requested-With, Content-Type, Accept'
  );
  next();
});

The snippet above showcases the yoga express server middleware that successfully tackled the problem at hand.

Answer №2

To successfully complete the task, I needed to pass an array of string values to the origin and also update the new origin value PAST_FRONTEND_URL in heroku

server.start(
  {
    cors: {
      credentials: true,
      origin: [process.env.FRONTEND_URL, process.env.PAST_FRONTEND_URL],
    },
  },
  deets => {
    console.log(`Server is now running on port http://localhost:${deets.port}`);
  }
);

Answer №3

After encountering the same issue, I managed to resolve it by implementing the following solution:

server.start(
  {
    cors: {
      credentials: true,
      origin: [process.env.FRONTEND_URL],
      methods: 'GET,HEAD,PUT,PATCH,POST,DELETE',
      preflightContinue: false,
      optionsSuccessStatus: 204
    }
  },
  server => {
    console.log(`Server is running on http://localhost/${server.port}`);
  }
);

Answer №4

In my situation, implementing this middleware made a significant difference:

server.express.use((req, res, next) => {
  res.header('Access-Control-Allow-Credentials', true)
  next()
})

Answer №5

To prevent browser complaints, the Server Application needs to include

Access-Control-Allow-Origin: YOUR_DOMAIN
in the response header.

An easy way to achieve this is by using middleware.

app.use(function(req, res, next) {
  res.header("Access-Control-Allow-Origin", "YOUR-DOMAIN"); // Make sure to replace 'YOUR-DOMAIN' with your actual domain
  res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
  next();
});

Alternatively,

const cors = require('cors')
const corsOptions = {
    origin: [
        "http://YOUR-DOMAIN"
    ],
    credentials: true
}
app.use(cors(corsOptions))

If you have already followed these steps and are still facing issues,

the problem might be due to a corrupted response.

It's possible that your server encountered an exception while sending the response or restarted before the response was fully delivered to the client. Another potential cause could be issues with your ISP or VPN blocking certain requests. :)

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

Printing keys of objects in an array in AngularJS through iteration

Here is an array of objects that I am attempting to iterate in ng-repeat and print keys, but I am facing some challenges. $scope.directivesInfo = [ {"ngRepeat": {"enter": true, "leave": true, "move": true, "add": false, "remove": false}}, {"ngView ...

Tips for customizing the background color of hyperlinks

Hello, I am trying to figure out how to create a hyperlink with alternating background colors. Can anyone guide me on achieving this? <div class="left_column"> <div class="category"> <p>Category</p> </div> <ul ...

Leveraging $scope methods from a separate controller within AngularJS

I want to transfer the $scope functions from one controller to another controller, specifically for an AngularUI dialog. In this scenario, I need $scope.scopeVar to be accessible in PopupCtrl. Check out this Plunkr Solve the code as per mlarcher's ...

In the realm of React Native, an error arises when attempting to access 'this._nativeModule.isBluetoothEnabled', as the reference to null prevents it from

Recently, I delved into working with react native and attempted to incorporate react-native-bluetooth-classic into my project. The URL for the API overview can be found here. However, I encountered an issue that has me stuck: "TypeError: null is not ...

Achieve full implementation of ng-repeat within an angular directive

Can you explain how the custom angular directive 'myscroll' is able to detect and interact with the ng-repeat elements that are dynamically created in the code snippet below? <myscroll> <div ng-repeat="item in items">{{item}}< ...

Tips for automatically verifying coupons and adjusting prices

My current task involves implementing a coupon feature on the checkout page using an AJAX request to validate the coupon and adjust the price accordingly. However, when the checkout view is loaded, I encounter an error message: The first argument in the ...

The challenges of implementing view changes with $state.go

In the code below, I am setting up a login process. The PHP file for this process is working correctly, but after successful login, the view does not change as expected: (function (){ var app = angular.module('starter', ['ionic']); va ...

Error encountered: TypeScript/Knex - The import statement can only be used inside a module

I am new to TypeScript and currently utilizing Knex to construct a template table in our PostgreSQL database. I keep encountering the same issue with TypeScript on this file and others, here is the code snippet: import * as Knex from 'knex'; ex ...

Efficiently clear input field values by clicking the remove button

Hey there, I'm currently facing an issue with my WordPress database. I have a file named add_field.php and scripts.js where I dynamically add input fields upon clicking the add more button and save the data into the database. However, I'm struggl ...

What is the best way to trigger a parent function from a Bootstrap modal within a Vue.js component

In my vue.js component, I am calling a Bootstrap modal within a function. I want to call another function after the modal is closed, but I am facing issues with the scope. this.myFunction() // This works here $('#app-modal-warning').on('hi ...

Top method for identifying genuine users and preventing bots

Utilizing a Maps API can be costly, especially with the fees per request To minimize requests, I heavily rely on caching techniques The API is invoked on every pageload, but unnecessary for non-human users like googlebot What would be the most effective ...

When updating a table in MySQL, use foreign key constraints to automatically populate another table with corresponding data

My situation involves working with two tables: users and login. Here's how they are structured: Create table users( id int not null, name varchar not null, email varchar not null, password varchar not null, entries int default 0, primary key(id) ...

The horizontal scrolling feature in tables is not functioning properly on iOS Safari

Having trouble getting a horizontal scroll to work on my table in a React app, specifically on iOS Safari. It works fine on other platforms. Here is a snippet from my JS file: <div className={styles.parent}> <div className={styles.wrapper}> ...

Is there a way to implement a polyfill for DOMParser on Web Worker in order to utilize it for uploads with the AWS S

Our team has implemented the AWS S3 SDK for uploading files from a browser to S3 buckets. To prevent UI rendering and interaction issues caused by large file uploads, we decided to move the upload process into a Web Worker thread. This solution allows user ...

How can you assign a value to an HTML Input by dragging an SVG shape or canvas?

I am currently in the process of creating a user interface for setting pricing parameters. There are three categories that need to be visually represented, along with two sliders to determine suggested Buy/Sell prices. To demonstrate my progress so far, I ...

Is there a way to utilize a POST request to pass a React component from server.js to App.js for rendering?

I am new to React and JavaScript and still in the learning process :) I'm working on a magic 8 ball application where, upon clicking the button using the post method, I aim to retrieve a random answer (one of the 20 in my server.js) back to the same ...

Firefox fails to identify the text inputted into the textbox

Encountered a situation where Firefox was not entering text in a required textbox within a popup. Upon clicking the button, a warning flag appears indicating that the field is mandatory. After inspecting the HTML code, it was revealed that there was no val ...

Learning how to retrieve information from Firebase Realtime Database using Vue.js

I am currently facing an issue while trying to console.log the documents from my Firebase real-time database. When attempting this, I encounter the following error: [Vue warn]: Error in created hook: "TypeError: firebase__WEBPACK_IMPORTED_MODULE_2__. ...

JavaScript: Issue with hiding input BUTTON element - still not resolved

<input id="btnupdate" type="button" value="Update" onclick="update()"/> <img id="loadupdate" src="http://localhost/connectu/styles/images/load_big.gif"> This particular HTML code snippet is generated by a PHP script in response to an AJAX requ ...

The functionality of GET_POST is not functioning properly

I've encountered an issue with my PHP webpage and JavaScript function: function send_answer(){ $.ajax({ type: 'POST', url: '../path2file/file_mine.php', data: {dbf1:1, us:1, re:1}, success: relo ...