The CORS preflight response does not align with the actual response received

In my node.js server, I have implemented CORS as middleware in the following manner:

app.use(cors({ origin: 'http://<CORRECT_ORIGIN_URL>:3030', credentials: true }))

Within my app, I am utilizing Apollo Client to send requests. During the initialization of ApolloClient, I have configured credentials to 'include' as shown below:

// Create a WebSocket link
const wsLink = process.browser ? new WebSocketLink({
    uri: `ws://<CORRECT_REQUEST_URL>:8000/graphql`,
    options: {
        reconnect: true,
    },
}) : null

// Create an http link (use batch, allow cookies response from server)
const httpLink = new BatchHttpLink({
    uri: 'http://<CORRECT_REQUEST_URL>/api/',
    credentials: 'include'
})


// Split terminating link for websocket and http requests
const terminatingLink = process.browser ? split(
    ({ query }) => {
        const { kind, operation } = getMainDefinition(query)
        return kind === 'OperationDefinition' && operation === 'subscription'
    },
    wsLink,
    httpLink,
) : httpLink

// Create Apollo client
const client = new ApolloClient({
    link: ApolloLink.from([authLink, errorLink, terminatingLink])
})

Upon attempting to sign-in, I notice that a preflight OPTIONS request is sent and receives the correct response:

Request Headers (OPTIONS request)

Access-Control-Request-Headers: content-type
Access-Control-Request-Method: POST
Origin: http://<CORRECT_ORIGIN_URL>:3030
Referer: http://<CORRECT_ORIGIN_URL>/login

Response Headers (OPTIONS request)

Access-Control-Allow-Credentials: true
Access-Control-Allow-Headers: content-type
Access-Control-Allow-Methods: GET,HEAD,PUT,PATCH,POST,DELETE
Access-Control-Allow-Origin: http://<CORRECT_ORIGIN_URL>:3030
Connection: keep-alive
Content-Length: 0
Date: Wed, 20 Mar 2019 03:09:14 GMT
Server: nginx/1.15.5 (Ubuntu)
Vary: Origin, Access-Control-Request-Headers
X-Powered-By: Express

However, when the actual POST request is made, the response headers differ as follows:

Response Headers (POST request)

Access-Control-Allow-Credentials: true
Access-Control-Allow-Origin: *
Connection: keep-alive
Content-Encoding: gzip
Content-Type: application/json
Date: Wed, 20 Mar 2019 03:09:15 GMT
Server: nginx/1.15.5 (Ubuntu)
Transfer-Encoding: chunked
Vary: Accept-Encoding, Origin
X-Powered-By: Express

The discrepancy in response headers during the POST request is causing an issue, leading to the following error message on the client side:

Access to fetch at 'http://<CORRECT_REQUEST_URL/api/' from origin
'http://<CORRECT_ORIGIN_URL>:3030' has been blocked by CORS policy: 
The value of the 'Access-Control-Allow-Origin' header in the response 
must not be the wildcard '*' when the request's credentials mode is
'include'.

I have conducted research online but have been unable to find a solution on platforms like Stack Overflow. Any suggestions or insights into this matter would be greatly appreciated.

Answer №1

Problem solved!

The issue was pinpointed to Apollo Server's default inclusion of CORS middleware, which was conflicting with my own CORS settings. As stated in Apollo's documentation:

If you provide false, the CORS middleware will be removed completely, and if you use true, it will adopt your middleware's default configuration.

The default setting is true.

To tackle this problem, I simply disabled the CORS feature within Apollo by specifying cors: false when utilizing .applyMiddleware as shown below:

server.applyMiddleware({
    app,
    path: '/',
    cors: false,
});

For more insights, check out:

Answer №2

Dealing with similar challenges, I encountered issues with my Apache2 proxy setup in front of my Express services. It seemed that the proxy was caching certain responses, causing some inconsistencies. To address this issue, I made modifications to my Apache configuration which effectively resolved the problem:

Header set Cache-Control "no-cache, must-revalidate"    env=no-cache-headers
Header set Pragma        "no-cache"                     env=no-cache-headers
Header set Expires       "Sat, 1 Jan 2000 00:00:00 GMT" env=no-cache-headers

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

What is the best practice for storing angular partials - should they be kept in the public/ directory, views/ directory, or another location altogether

Currently developing a Pinterest-inspired platform to enhance my understanding of node.js. I'm contemplating where to store my partial views, such as those for rendering pins - should they be placed in the public/partials folder or within the views/ d ...

Leveraging the api.call function to parse JSON data in a nodejs

I'm currently working on extracting data from a JSON response obtained through an API. Although I am able to stringify the response, I'm facing difficulties in parsing the JSON data and specifically retrieving the value of "display_name" into a v ...

Determining the optimal scenarios for utilizing debug compared to alternative logging frameworks

NodeJS offers two well-known logging frameworks: winston and Bunyan. Additionally, there is a tool called debug. From my understanding, all of these tools essentially serve the same purpose - which is to log information. debug comes as a default component ...

How can data be transmitted to the client using node.js?

I'm curious about how to transfer data from a node.js server to a client. Here is an example of some node.js code - var http = require('http'); var data = "data to send to client"; var server = http.createServer(function (request, respon ...

Is there a way to run a node script from any location in the command line similar to how Angular's "

Currently, I am developing a node module that performs certain functions. I want to create a command similar to Angular's ng command. However, I am facing compatibility issues with Windows and Linux operating systems. Despite my attempts to modify the ...

I'm facing a challenge where Multer is preventing me from showing images in my React app

Hi there, I'm currently facing an issue where I am using multer to save files on my server and store their path in mongodb. However, I am struggling to display them on my React application. Any assistance would be greatly appreciated. Thank you in ad ...

Tips for sending information in node.js using the content type of 'application/x-protobuf'

Having trouble sending data with content-type='application/x-protobuf'. Is it possible to request protobuf through an HTTP request? If so, how can this be achieved? ...

Step-by-step guide on integrating node.js and MySQL to store data from an online form in a database

Currently, I am attempting to insert data into a MySQL database using node.js by clicking the submit button. However, an error message has appeared and despite understanding it somewhat, I am unsure of how to proceed. Any assistance would be greatly apprec ...

Saving base64 data directly to a mongoose database in an Express.js server can be achieved by

I am facing a challenge where I need to store an image directly in my database instead of on the server. Here is the model I am using: var mongoose = require('mongoose'); var Schema = mongoose.Schema; var categorySchema = new Schema({ img ...

Navigating the Promise Flow in NodeJS: Tips for Regulating Execution

I am trying to gain a better understanding of nodeJS by using the following code to execute CMD operations one by one. However, I have noticed that due to the event loop, it gets executed in random variations. Here is my code: const exec = require('c ...

The vulnerabilities within npm installations can vary greatly depending on the specific project being considered

Is it possible for the same node package to result in two different audit outcomes when installed on two separate projects? One project shows no vulnerabilities while the other has two. I am willing to provide more information about the nature of the proj ...

NodeJS archival system

I am looking to extract the contents of archives without having to first unzip them in order to see what's inside. Specifically, I am interested in being able to list and uncompress files from formats like zip and rar, though I am open to other option ...

Running a Node Fetch POST call with a GraphQL query

I'm currently facing an issue while attempting to execute a POST request using a GraphQL query. The error message Must provide query string keeps appearing, even though the same request is functioning correctly in PostMan. This is how I have configur ...

Encountering errors: Time-zone discrepancies arise when making API calls from AngularJS and querying results from Firebase using NodeJS

Whenever I try to query with a date range, the results returned are incorrect. I have implemented DateRangePicker jQuery for selecting both date and time ranges. After that, I make an API call and send my date/Moment JS object to my Node.js API where I q ...

Querying a MongoDB collection for a specific entry based on its ID

Is it possible to update a user story in a project using MongoDB? I am looking to update the fields of a specific user story within a project by selecting the project based on its id and then selecting the user story within that project based on its id. ...

Switching the GET method to DELETE in nodeJS can be accomplished using an anchor tag

Let's say I have a link in my EJS file like this: <a href="/user/12">Delete</a> In my route file, I have the delete code set up like this: router.delete( '/user/:id', function ( req, res ) { // code for delete operation }); ...

Buffer Overflow - Security Audit - Node JS TypeScript Microservice Vulnerability Scan Report

Person Data Schema: import JoiBase from '@hapi/joi'; import JoiDate from '@hapi/joi-date'; const Joi = JoiBase.extend(JoiDate); const personDataSchema = Joi.object().keys({ person: Joi.object().keys({ personId: Joi.string().max( ...

Is it advisable to refrain from handling all routes in a Node/Express application using an asterisk?

Recently, I set up a simple node app that captures all incoming requests: app.get('*', function(req, res) { //handle GET request with specific parameter } I'm wondering if there are any drawbacks to using this catchall method if the app ...

When running the command `npm start`, an error message is generated

Hey everyone, I've been trying to learn some basic AngularJS 2.0 skills through a tutorial. Unfortunately, when I tried running the command npm run start, it didn't work as expected. I'm currently using Git Bash on Windows 10 OS. If you hav ...

The installation of npm encountered an error. For a detailed log of this process, please refer to the complete log file within the

I am encountering issues with installing the react app. After running npm install, I am receiving multiple errors in the terminal. npm ERR! code 1 npm ERR! path C:\Users\Yaya\Desktop\ATL\detexter-web-front\node_modules\no ...