问答

vue axios访问外部API报错如何解决

作者:admin 2021-06-22 我要评论

后端是Express,CROS也设置了跨域请求(因为前端在8080,后端3000,这俩互通没有问题), app.all('*', function(req, res, next) { // CORS headers res.header...

在说正事之前,我要推荐一个福利:你还在原价购买阿里云、腾讯云、华为云服务器吗?那太亏啦!来这里,新购、升级、续费都打折,能够为您省60%的钱呢!2核4G企业级云服务器低至69元/年,点击进去看看吧>>>)

后端是Express,CROS也设置了跨域请求(因为前端在8080,后端3000,这俩互通没有问题),

app.all('*', function(req, res, next) {
  // CORS headers
  res.header("Access-Control-Allow-Origin", "*"); // restrict it to the required domain
  res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS');
  // Set custom headers for CORS
  res.header('Access-Control-Allow-Headers', 'Content-type,Accept,X-Access-Token,X-Key');
  if (req.method == 'OPTIONS') {
    res.status(200).end();
  } else {
    next();
  }
});

但是用第三方API的时候:

//vue中
  mounted () {
    axios
      .get('https://api.bilibili.com/x/web-interface/view?aid=xxxxxx')
      .then(response => (this.info = response))
  }

浏览器报错:

Access to XMLHttpRequest at 'https://api.bilibili.com/x/web-interface/view?aid=xxxxxx' from origin 'http://localhost:8080' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

我是想在前端通过b站的API来获取up主/标题/封面信息,不保存在数据库来着,想问问大佬们这个怎么解决呀。

###

既然都使用了 express ,那就索性使用代理

express:

const { createProxyMiddleware } = require('http-proxy-middleware');

app.use(
  '/bilibili',
  createProxyMiddleware({ target: 'https://api.bilibili.com', changeOrigin: true })
);

html/vue

  <script src="/uploads/allimg/210622/1232012X6-0.jpg"></script>

  <script>
    axios
      .get('/bilibili/x/web-interface/view?aid=xxxxxx')
      .then(response => {
        console.log(response)
      }).catch(err => {
        console.log(err)
      })
  </script>

image.png

###

跨域了啊,客户端访问不了的。可以用 Node.js 在服务端访问。

###

经过你的后端服务(express)进行代理

###

你这个是直接用浏览器,请求的 bilibili的接口,B站当然会有限制, 你可以用后端做一层转发请求。

版权声明:本文转载自网络,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。本站转载出于传播更多优秀技术知识之目的,如有侵权请联系QQ/微信:153890879删除

相关文章
  • vue axios访问外部API报错如何解决

    vue axios访问外部API报错如何解决

  • Spring Security默认登录地址无法实现

    Spring Security默认登录地址无法实现

  • 前端的未来方向

    前端的未来方向

  • 怎么运行别人给的gulp项目

    怎么运行别人给的gulp项目

腾讯云代理商
海外云服务器