我正在尝试使用 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 应用程序。但任何帮助都会很棒!这可能是爵士乐的问题吗?