简体   繁体   English

Axios - 无“访问控制允许来源” - CORS

[英]Axios - No 'Access-Control-Allow-Origin' - CORS

I'm building a javascript app which uses an external API.我正在构建一个使用外部 API 的 javascript 应用程序。 To get the data, I use axios, but whenever I make a request it returns a CORS error - "No Access-Control-Allow-Origin header set".为了获取数据,我使用 axios,但每当我发出请求时,它都会返回 CORS 错误 - “没有访问控制允许来源 header 设置”。 Now, a temporary solution is to add a third part proxy in front of the API URL (for example https://cors-anywhere.herokuapp.com ), and it works just fine, but I don't really want to depend on a third part server and would like to handle it inside my own app. Now, a temporary solution is to add a third part proxy in front of the API URL (for example https://cors-anywhere.herokuapp.com ), and it works just fine, but I don't really want to depend on第三方服务器,并希望在我自己的应用程序中处理它。

I've tried pretty much everything and still can't get it to work.我已经尝试了几乎所有方法,但仍然无法正常工作。 I've used axios response interceptors to attach required headers to the response, but it just doesn't work.我已经使用 axios 响应拦截器将所需的标头附加到响应中,但它不起作用。

axios.interceptors.response.use(res => {
  res.headers['Access-Control-Allow-Origin'] = '*';
  res.headers['Access-Control-Allow-Credentials'] = 'true'
  res.headers['Access-Control-Request-Method'] = 'POST'
  return res;
})

my server.js file looks something like this我的 server.js 文件看起来像这样

const serveStatic = require('serve-static')
const path = require('path')
const cors = require('cors');

const app = express()

app.use('/', serveStatic(path.join(__dirname, '/dist')))
app.use(cors());

const port = process.env.PORT || 8080
app.listen(port, () => console.log("starting on port 8080"));

Any solutions on this problem?关于这个问题的任何解决方案?

Try to invert the two lines:尝试颠倒这两行:

app.use(cors());
app.use('/', serveStatic(path.join(__dirname, '/dist')));

Tell me if it works告诉我它是否有效

By the way your interceptors is useless, you can remove it:顺便说一句,您的拦截器没用,您可以将其删除:

axios.interceptors.response.use(... 

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM