Troubleshooting the CORS problem with 'Access-Control-Allow-Origin' while combining Vue.js for the front-end and Express for the back-end

While attempting to make a call to my API on Jazz using Vue.js and Axios, I encountered the following error:

Access to XMLHttpRequest at ' _here' from origin 'http://localhost' 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.

I have explored various solutions like https://enable-cors.org/server_expressjs.html or including

"Content-Type": "application/json",
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Methods": "OPTIONS",
"Access-Control-Allow-Headers": "Content-Type, Authorization",
"Access-Control-Allow-Credentials": "true"

in my code with no success. Even after setting the wildcard for Access-Control-Allow-Origin, the CORS issue persists and I am unable to call my API. On the client side, I am utilizing Vue and Typescript, while Express powers the server side. Below is a snippet of my Axios API call:

return Axios.post('https://jazz.api.com/api/extra_stuff_here', context.getters.getRequest,
        {
          headers: {
            "Content-Type": "application/json",
            "Access-Control-Allow-Origin": "*",
            "Access-Control-Allow-Methods": "OPTIONS",
            "Access-Control-Allow-Headers": "Content-Type, Authorization",
            "Access-Control-Allow-Credentials": "true"
          }
        }
      )

This TypeScript file showcases where I make the API call, while this is my server.js:

var express = require('express');
var path = require('path');
var cors = require('cors');
var bodyParser = require('body-parser');
var morgan = require('morgan');

var app = express();
app.use(morgan('dev'));
app.use(cors());
app.use(bodyParser.json());

var publicRoot = './dist';

//app.use(express.static(path.join(__dirname, '/dist')));
app.use(express.static(publicRoot));

app.get('/', function (req, res) {
    res.sendFile("index.html", { root: publicRoot });
});

app.use(function(req, res, next) { 
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Authorization");
    res.header("Content-Type", "application/json");
    res.header("Access-Control-Allow-Methods", "GET, POST, OPTIONS");
    res.header("Access-Control-Allow-Credentials", "true");
    next();
}); 

app.listen(process.env.PORT || 80, function() {
    console.log("listening on port 80");
});

I'm struggling to resolve this CORS issue despite all attempts. Adding express did not alleviate the problem, even though I initially faced it before integrating express in my application. Previously, I ran my Vue application using npm run serve. Any advice on solving this issue would be greatly appreciated! Could it possibly relate to Jazz?

Answer №1

The cors middleware has been included in your code, but it hasn't been configured to handle OPTIONS requests

app.options('*', cors())

To enable handling of OPTIONS requests on your server, consider implementing the following code snippet. For more information, refer to the documentation in the express docs available at https://expressjs.com/en/resources/middleware/cors.html

Answer №2

Update: Despite my efforts, I was unable to resolve the CORS issue with Axios. However, I did discover a workaround for it. Instead of utilizing the Axios library, I switched to using fetch to make API calls. Since my request only involves passing parameters and receiving data based on those parameters, fetch serves my purpose effectively. During my exploration, I came across potential problems or limitations associated with fetch. Nonetheless, since it functions well for me, I have decided to continue with this approach. Below is the code snippet for reference:

return fetch('https://dev.jazz.com/api/stuff_goes_here', {
  method: 'post',
  body: JSON.stringify(<request object goes here>)
}).then((res) => res.json())
.then((data) => {
  return data;
}).catch((err)=>console.log(err))

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 way to show the previous month along with the year?

I need help with manipulating a date in my code. I have stored the date Nov. 1, 2020 in the variable fiscalYearStart and want to output Oct. 2020. However, when I wrote a function to achieve this, I encountered an error message: ERROR TypeError: fiscalYear ...

Strategies for capturing a 404 error in an Express router

Trying to capture the 404 page not found error in an express router. Using a simple example : const express = require('express'); const app = express(); const router = express.Router(); // ROUTER MID BEFORE router.use((req, res, next) => { ...

When exporting a Mongoose model, it mysteriously becomes undefined

I am encountering an issue when trying to import the DemandeTransports model from a specific file: //@/components/database/model/Schema.js import { Schema } from "mongoose"; import mongoose from "mongoose"; const userSchema = new Schem ...

Using Vue's v-if statement to determine if a variable is either empty or null

Using a v-if statement to display certain HTML only if the archiveNote variable is not empty or null. <div v-if="archiveNote === null || archiveNote ===''" class="form-check ml-3" id="include-note-div"> Here is how it's implemented ...

Create a fresh array by merging two existing arrays together

My project involves working with two separate arrays. The first array contains normal date values: var = [ "2022-05-01", "2022-05-02", ... "2022-05-30" ] The second array consists of objects that contain s ...

"Patience is key when waiting for an AJAX response within a jQuery loop

I've been facing difficulties in making this work using the $.Deferred object. Here is a simplified version of the code setup. g_plans = []; $(function(){ // Need to utilize a custom ajax function that returns a promise object var pageLoadPro ...

Transferring information between a pair of input fields using ngModel

There are two input fields named input1 and input2. An event has been created where anything typed in input1 is displayed in input2. However, if something is manually changed or typed into input2, the event should not trigger. I think I may need to use a ...

The concept of CSS sprites and managing background positions

I have been working on integrating a star-rating widget that requires the use of a sprite file. The sprite file I am using looks like this: https://i.stack.imgur.com/ZSMMj.png This is how my HTML is structured: HTML <span id="star-ratings" class="c ...

Incorporating VueJS with a sleek material design aesthetic

Currently, I am in the process of developing a web application using VueJs and am in need of a CSS framework to aid in designing without starting from scratch! After some research, I came across material-design-lite (www.getmdl.io) but unfortunately faced ...

`Creating a functional list.js filter``

I'm having trouble making the List.js filter function work properly. The documentation for List.js is not very helpful for someone new to development. Below is the code I am using: HTML: <div class="col-sm-12" id="lessons"> <input class= ...

Updating a specific index within an array of objects in a Mongoose-Express server

I have set up a unique identifier ID and I am attempting to modify my coins as well as the first array object's purchased boolean value to true. This is an example of how my data appears: [ { "identifier": "123456789&q ...

How to retrieve an object once it exits the viewport in JavaScript

I am seeking guidance on how to reset an object to its initial position (0) once it exits the browser window. Currently, I have an image that moves when you click on the up/down/left/right buttons, but it eventually extends beyond the browser window. Belo ...

Node-powered Angular

Currently working on setting up client-side routing with AngularJS and Node. Ran into some issues along the way. EDIT After making changes to my code based on recommendations from @PareshGami, following https://github.com/scotch-io/starter-node-angular, I ...

The option chosen from the ng-options does not remain attached to the drop-down menu

I need some help with AngularJS as I am still getting the hang of it. Take a look at this not-so-pretty page: This page allows users to add new beers, and each beer can have multiple styles. Clicking 'Add' creates a new dropdown for selecting a ...

Leveraging jest for handling glob imports in files

My setup involves using webpack along with the webpack-import-glob-loader to import files utilizing a glob pattern. In one of my files (src/store/resources/module.ts), I have the following line: import '../../modules/resources/providers/**/*.resource. ...

The website flickers in and out as it loads

My site keeps flashing whenever it loads. Despite trying the solutions recommended in this stackoverflow post, I have had no success. Every page on my website loads a nav.html file using this code: $.get("nav.html", function(data){     $("#nav-placeho ...

Steps for resetting a div's display after adjusting the device size

I have a code that displays horizontally on desktop screens and vertically on phones. It includes an x button (closebtn) that is only displayed on phones to close the menu bar. How can I automatically display it again after resizing the page back to deskto ...

Unconventional login processes showcased in Redux-Saga's documentation

When looking at the login flow example in the redux-saga documentation, it is clear that the expected action sequence is well-defined. However, does the LOGOUT action always follow the LOGIN action? In real-world scenarios, such as when a user's sessi ...

The creation of the express-session session table has failed

Hello, I am encountering an issue with express session. The code functions properly on my laptop, but when I attempt to save the session to a different database on another system, the sessiontbl is not being automatically created. Here is my app.js: cons ...

Is it possible to use wildcards in Socket.io rooms or namespaces?

The hierarchy I am working with is as follows: Store -> Manager -> Assistant In this setup, a Manager has access to everything that the Assistant sends, while the Assistant can only access what the Manager explicitly provides. My understanding is t ...