"Despite not preferring to use the CORS wildcard, I am encountering a CORS wildcard error

I'm currently in the process of developing a web application using node, express, and Vue3

My goal is to submit a form to an endpoint located on my router at '/match/matchpost'. I have previously tested this endpoint successfully. However, after setting up SSL, I started encountering the following errors:

r.js:247     GET https://localhost:5173/ net::ERR_FAILED
dispatchXhrRequest @ xhr.js:247
xhr @ xhr.js:49
dispatchRequest @ dispatchRequest.js:51
request @ Axios.js:142
httpMethod @ Axios.js:181
wrap @ bind.js:5
submitForm @ MatchForm.vue:18
(anonymous) @ MatchForm.vue:78
(anonymous) @ runtime-dom.esm-bundler.js:1483
callWithErrorHandling @ runtime-core.esm-bundler.js:173
callWithAsyncErrorHandling @ runtime-core.esm-bundler.js:182
invoker @ runtime-dom.esm-bundler.js:345

...

<p>The browser console seems to be indicating that a GET request is being made, despite my intention to make a POST request as shown here:</p>
<pre><code>axios.post("https://localhost:8080/match/matchpost",{
                title: this.title,
                game: this.game,
                description: this.description,
                rules: this.rules,
                participantNum: this.participantNum,
            },{
                headers:{
                    'Content-Type' : 'application/json'
                },
                withCredentials: true
            })
            .then(response => {
                console.log(response);
            })
            .catch(error => {
                console.log(error);
            });
...

It appears that these are not the only issues, but most likely stem from the CORS error warning about wildcards and credentials. Despite my efforts to address this issue by avoiding wildcard usage, it persists.

I've extensively researched similar problems and attempted various CORS configurations without success.

I initially configured CORS per router basis, then consolidated all configurations into one file and imported where needed but the problem persists.

Below is the CORS configuration:

const cors = require('cors');

const corsOptions = {
  origin: 'https://localhost:5173',  
  credentials: true,
  methods: ['GET', 'POST', 'OPTIONS', 'PUT', 'DELETE', 'HEAD'],
  allowedHeaders: ['auth-token', 'Origin', 'X-Requested-With', 'Content-Type', 'Accept'],
  preflightContinue: true,
};

const corsMiddleware = cors(corsOptions);

module.exports = corsMiddleware;

Here is how I import the CORS middleware:

match.use(corsMiddleware);
match.options('*', corsMiddleware);

If more information is required, please do not hesitate to ask. I appreciate any assistance or insights you can provide. Thank you!

Answer №1

Experiencing CORS issues while testing on localhost can be quite challenging. Certain scenarios may not function as expected.

In this particular situation, the issue seems to arise from performing a redirect within your POST handler.

Upon receiving a redirect response to a POST request, the request is ultimately resent as a GET request (this behavior varies based on the specific response code received - for example, a 303 response will always redirect as a GET, and a 301 should prompt user interaction).

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

Validate input strings in Node.js using Joi to detect and return an error if there are leading or trailing spaces

Looking to set up JOI validation in Node.js that flags errors if a string begins or ends with an empty space. For example: name = "test123" //valid name = "test(space)" or "(space)test" // invalid ...

Is it possible to use a string instead of an array for the command in node

Currently, I'm tackling the spawn function in Node.js. In the past, I relied on exec, but faced issues with its compatibility when it comes to streaming stdout (or stderr). Now, my challenge lies in adapting to spawn. Unlike exec, which accepted quote ...

I am struggling with sending post requests in Node.js

I am currently facing a challenge with handling form data from a webpage using Node.js and writing that data to a file. It seems like there might be an issue with how Node.js is processing my POST request, or perhaps the way I am sending the request from t ...

The issue of ECONNABORTED is being triggered by parameterized queries

Attempting to execute a GET request from the front end to retrieve the username in the row where user_id = 1 using parameterized queries. While hard-coded queries are functioning correctly, parameterized queries result in the request being terminated and d ...

The ultimate guide to loading multiple YAML files simultaneously in JavaScript

A Ruby script was created to split a large YAML file named travel.yaml, which includes a list of country keys and information, into individual files for each country. data = YAML.load(File.read('./src/constants/travel.yaml')) data.fetch('co ...

NodeJS - Retrieving image file size from source shows inaccurate results

I have a simple query regarding the size discrepancy of files when read using fs.readFileSync, particularly when the source path points to an image or non-text file. For instance: fs.writeFileSync(outputPath, fs.readFileSync(source, 'utf8')); ...

Is it possible to alter the video dynamically according to the state in Vuex?

I am working on a small web application that mimics the appearance of FaceTime. My goal is to switch between video elements by clicking a "Next" button, which will update a value in Vuex and swap out the video accordingly. I initially attempted this appr ...

The reason behind using the /public directory for serving static content in Node.js

When using node.js with express, all the static content is typically placed in the /public folder. However, what if I prefer to create a folder called 'static' within the 'views' folder and keep all images, styles, and script files in i ...

Encountering an authentication issue in Active Directory while using Express.js

I've encountered a unique issue while using the activedirectory module for user authentication with AD. While most users authenticate without any problems, users within a specific OU are constantly facing authentication failures. Below is the code sni ...

Not defined within a function containing arrays from a separate file

Can anyone help me with listing multiple arrays from another file? When I try to iterate through each array using a "for" loop, the code compiles and lists everything but gives an undefined error at the end. How can I fix this? I have included some images ...

What is the resolution if I need to utilize a property that is untyped?

Transitioning to TypeScript from plain old JavaScript is a step I'm taking because I believe it offers significant advantages. However, one drawback that has come to light is that not all attributes are typed, as I recently discovered. For instance: ...

Wait for NodeJS to finish executing the mySQL query

I am attempting to send an object from the controller to the view. To keep my queries separate from the controller, I am loading a JS object (model). My model structure is as follows: function MyDatabase(req) { this._request = req; this._connection = ...

What steps can I take to make the replaceData function function properly?

Struggling to implement replaceData, setData, or updateData functions in my project. I am using bootstrap vue along with tabulator tables. The API is functioning correctly. Tabulator works smoothly unless the API URL depends on the modal select option; how ...

Access the localhost:3000 webpage in kiosk mode once the Node.js server has fully started running

Currently, I am immersed in a Raspberry Pi project which requires me to operate a node server in kiosk mode. To prevent the default localhost opening upon server execution, I have implemented BROWSER=none. My intention is to use wait-on to ensure that th ...

WebStorm not recognizing NodeJS Core Modules in External Libraries

As a newcomer to NodeJS and WebStorm, I am currently diving into a tutorial on creating an Express app. In the tutorial, the instructor always gets prompted with "Configure NodeJS Core Module Sources" including the URL nodeJS.org when creating a new NodeJ ...

I need assistance with using regex to extract values enclosed in quotes

After spending almost a full day attempting to create a RegEx for a specific string, I have yet to make it work. Can someone offer assistance? string example (double quotes are options, and can also be single quotes): "234"? "<img src=\"http:/ ...

I successfully made a GET request using Postman, but encountered an issue when trying to do the same request through a

Currently, my objective is to send URL encoded parameters through a GET request using the fetch function. To achieve this, I am attempting to display the parameters via Express in the following manner: app.get('/api', function (req, res) { c ...

Learn the process of integrating content into a tinymce editor using vue js

Is there a way I can use a button in the vue js template to insert content like <span class="some-class">text</span> inside tinymce editor with the help of the tinymce-vue wrapper? Here is the code snippet: <template> <tiny ...

What could be causing the 404 error message in Backend deployment on Vercel?

Hello everyone, I'm currently in the process of deploying the backend for my MERN application on Vercel. Prior to this attempt, I successfully deployed a small todo project using MERN on Vercel. Everything worked fine then, and I followed the same st ...

Make multiple axios.get requests to retrieve and show data from the specified endpoint repeatedly

I am currently working on a backend built in Flask that provides a REST API for various tasks, one of which involves requesting deployment. Once the request is made, logs are stored in the database. To address this, I have created another REST API endpoint ...