简体   繁体   English

将Vue.js用于客户端而Express用于服务器端时出现“Access-Control-Allow-Origin”CORS问题

[英]“Access-Control-Allow-Origin” CORS issue when using Vue.js for client side and Express for server side

I'm trying to make a call to my API on Jazz using Vue.js and Axios, but I am getting the following error: 我正在尝试使用Vue.js和Axios在Jazz上调用我的API,但是我收到以下错误:

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. 从' http:// localhost '访问来自' https://jazz.api.com/api/extra_stuff _here'的XMLHttpRequest已被CORS策略阻止:对预检请求的响应未通过访问控制检查:否' Access-Control-Allow-Origin'标头出现在请求的资源上。

I've been looking at other solutions like https://enable-cors.org/server_expressjs.html or adding 我一直在寻找其他解决方案,如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"

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. 即使我为Access-Control-Allow-Origin执行通配符,我仍然会遇到CORS问题而无法调用我的API。 I am using Vue and Typescript for the client side and managed to get Express working for my server side. 我正在为客户端使用Vue和Typescript,并设法使Express在我的服务器端工作。 Here is a code snippet of my Axios API call: 以下是我的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"
          }
        }
      )

This is where I am calling my API in this TypeScript file and here is my server.js: 这是我在这个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");
});

No matter what I seem to do, I cannot figure out this CORS issue. 无论我做什么,我都无法弄清楚这个CORS问题。 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. 在我向我的应用程序添加express之前,我仍然遇到了同样的问题,认为可能在服务器端表达可能会解决CORS问题。 However it didn't help. 但它没有帮助。 Beforehand, I was running my Vue application by doing npm run serve. 事先,我通过执行npm run serve来运行我的Vue应用程序。 But any help would be great! 但任何帮助都会很棒! Could it possibility be an issue with Jazz? 这可能是爵士的问题吗?

You've added the cors middleware but haven't enabled it for OPTIONS requests 您已添加了cors中间件但尚未为OPTIONS请求启用它

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 您可以在快速文档中进一步阅读https://expressjs.com/en/resources/middleware/cors.html

Update: I didn't manage to fix the CORS issue with Axios, but I did manage to find a workaround for this. 更新:我没有设法修复Axios的CORS问题,但我确实设法为此找到了解决方法。 Instead of using the Axios library, I am using fetch to call the API. 我没有使用Axios库,而是使用fetch来调用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 . 由于我需要执行的所有请求调用是传递参数并根据参数获取数据,因此我的应用程序可以使用fetch While I was doing my research, I saw that there may be issues or limitations using fetch ? 在我进行研究时,我发现使用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))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何使用JavaScript解决客户端的问题“ No&#39;Access-Control-Allow-Origin&#39;header” - how to resolve issue “No 'Access-Control-Allow-Origin' header ” on client side using javascript Nodejs Express CORS 问题与“Access-Control-Allow-Origin” - Nodejs Express CORS issue with 'Access-Control-Allow-Origin' Express.js中的条件CORS Access-Control-Allow-Origin - Condition CORS Access-Control-Allow-Origin in Express.js 配置服务器端CORS:ExpressJS不存在“ Access-Control-Allow-Origin” - Configure server-side CORS: ExpressJS No “Access-Control-Allow-Origin” is present 受客户端和访问控制允许来源限制的Javascript - Javascript limited by client-side and access-control-allow-origin 没有“ Access-Control-Allow-Origin”客户端修复 - No 'Access-Control-Allow-Origin' client side fix 如何解决vue.js中的“ Access-Control-Allow-Origin”-问题? - How to solve “Access-Control-Allow-Origin”-Issue in vue.js? CORS - 访问控制允许来源问题 - CORS - Access-Control-Allow-Origin issue CORS标头“ Access-Control-Allow-Origin”丢失。 我需要在webapi(服务)或客户端编写代码的地方 - CORS header ‘Access-Control-Allow-Origin’ missing' . where i need to write code in webapi (service) or in client side 尽管启用了 CORS,但在 express js 上 CORS api Access-Control-Allow-Origin - CORS on express js api Access-Control-Allow-Origin despite CORS enabled
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM