0

我正在尝试使用 Vue.js 和 Axios 在 Jazz 上调用我的 API,但出现以下错误:

从源“ http://localhost ”访问“ https://jazz.api.com/api/extra_stuff_here ”的 XMLHttpRequest已被 CORS 策略阻止:对预检请求的响应未通过访问控制检查:否Access-Control-Allow-Origin' 标头出现在请求的资源上。

我一直在寻找其他解决方案,例如https://enable-cors.org/server_expressjs.html或添加

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

到我的代码,它仍然没有工作。即使我为 Access-Control-Allow-Origin 使用通配符,我仍然会遇到 CORS 问题并且无法调用我的 API。我在客户端使用 Vue 和 Typescript,并设法让 Express 为我的服务器端工作。这是我的 Axios API 调用的代码片段:

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

这是我在这个 TypeScript 文件中调用我的 API 的地方,这是我的 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");
});

无论我做什么,我都无法弄清楚这个 CORS 问题。在我将 express 添加到我的应用程序之前,我仍然遇到同样的问题,认为服务器端的 express 可能会解决 CORS 问题。然而它并没有帮助。之前,我通过执行 npm run serve 来运行我的 Vue 应用程序。但任何帮助都会很棒!这可能是爵士乐的问题吗?

4

2 回答 2

3

您已添加 cors 中间件,但尚未为 OPTIONS 请求启用它

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

尝试将类似的内容添加到您的服务器以启用它。您可以在此处的快速文档中进一步阅读 https://expressjs.com/en/resources/middleware/cors.html

于 2018-12-21T00:33:40.780 回答
2

更新:我没有设法解决 Axios 的 CORS 问题,但我确实找到了解决方法。我没有使用 Axios 库,而是使用fetch调用 API。由于我对请求调用所需要做的就是传入参数并根据参数取回数据,因此我的应用程序使用fetch. 在我进行研究时,我发现使用fetch?可能存在问题或限制。但是,嘿,它对我有用,所以我会坚持使用这个解决方案。这是我的代码供任何人参考:

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))
于 2018-12-29T01:09:06.730 回答