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?