-->

“Access-Control-Allow-Origin” CORS issue when usin

2019-08-01 13:36发布

问题:

I'm trying to make a call to my API on Jazz using Vue.js and Axios, but I am getting the following error:

Access to XMLHttpRequest at 'https://jazz.api.com/api/extra_stuff _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've been looking at other solutions like https://enable-cors.org/server_expressjs.html or adding

"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"

to my code and it still didn't work. Even if I do the wildcard for the Access-Control-Allow-Origin, I still get the CORS issue and cannot call my API. I am using Vue and Typescript for the client side and managed to get Express working for my server side. Here is a code 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 is where I am calling my API in this TypeScript file and here 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");
});

No matter what I seem to do, I cannot figure out this CORS issue. Before I added express to my application, I still got the same issue, thinking that maybe express on the server side would fix the CORS issue. However it didn't help. Beforehand, I was running my Vue application by doing npm run serve. But any help would be great! Could it possibility be an issue with Jazz?

回答1:

You’ve added the cors middleware but haven’t enabled it for OPTIONS requests

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

Try adding something like this to your server to enable it. You can read further in the express docs here https://expressjs.com/en/resources/middleware/cors.html



回答2:

Update: I didn't manage to fix the CORS issue with Axios, but I did manage to find a workaround for this. Instead of using the Axios library, I am using fetch to call the API. Since all I need to do with my request call is to pass in parameters and get back data based on the parameters, my application works with fetch. While I was doing my research, I saw that there may be issues or limitations using fetch? But hey, it works for me so I'll be sticking with this solution. Here is my code as reference for anyone:

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))