Access to XMLHttpRequest at 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=wxe82a537964140103&secret=e80661eabe42dcef25dd2ff7c71accd8' from origin 'http://localhost:8080' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. 

遇到了以上报错,必然是跨域,浏览器同源策略的问题!!

那我们要怎么解决呢??

需要请求的完整路径:https://api.weixin.qq.com/cgi-bin/token

1、vue项目根目录新建 vue.config.js

2、vue.config.js 配置

module.exports = {
  devServer: {
    host: '0.0.0.0', //可以忽略不写
    port: 8080, //它是用来修改你打开后的端口号的
    open: true, //值为 true的话,项目启动时自动打开到浏览器里边, false不会打开
    proxy: {
      '/api': {
        target: 'https://api.weixin.qq.com', //跨域请求的公共地址
        ws: false, //也可以忽略不写,不写不会影响跨域
        changeOrigin: true, //是否开启跨域,值为 true 就是开启, false 不开启
        pathRewrite: {
          '^/api': '' //注册全局路径, 但是在你请求的时候前面需要加上 /api
        }
      }
    }
  }
}

vue3中vite代理配置

export default defineConfig({
  server: {
    port: 5173, // 启动本地服务显示IP
	host: "0.0.0.0",
    proxy: {
      '/api': {
        target: 'http://127.0.0:8080/',
        changeOrigin: true,
        rewrite: (path) => path.replace(/^\/api/, ""),
      }
    }
  },
  plugins: [
    vue(),
  ],
  resolve: {
    alias: {
      '@': fileURLToPath(new URL('./src', import.meta.url))
    }
  }
})

  3、直接访问 /api/cgi-bin/token 相当于访问  http://localhost:8080/api/cgi-bin/token

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐