美文网首页
前端跨域问题的解决思路

前端跨域问题的解决思路

作者: 639c12a85b17 | 来源:发表于2022-06-24 17:50 被阅读0次

    前言

    做了一个简单页面,做了一些数据埋点,想通过企业微信机器人来推送数据,遇到了一些问题,顺便记录下。

    跨域问题的解决思路

    由于是项目比较简单,直接使用了ajax去请求,代码如下

    $.ajax({
      type: 'POST',
      url: 'https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=b38aa4d8-a08e-4a91-',
      async: true,
      data: $.toJSON(data),
      contentType:'application/json;charset=utf-8',
      dataType: 'json',
      success: function (data) {
        console.log("data",data)
      },
      error: function (error) {
        console.log("error",error);
      }
    })

    请求的时候发现了跨域问题

    Access to XMLHttpRequest at 'https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=b38aa4d8-a08e-4a91-' from origin 'null' 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.

    这里为什么会跨域呢?因为我在我自己域名上去请求其他域名。

    一般跨域的解决方案

  1. • jsonp(维信机器人接口只支持json)

  2. • 后端设置跨域 (改不了微信接口的后台)

  3. 那有什么方案呢?

    思路决定出路。

    先明白问题所在,是因为浏览器同源政策导致跨域的问题,那我请求的域名是同源的不就好了吗?

    下面说下具体方法

  4. • 使用nginx进行转发

  5. 我只需要把ajax请求的url更换成自己的域名,然后使用nginx转发到企业微信接口,就完美绕开了跨域问题

    $.ajax({
      type: 'POST',
      url: 'https://domain/test',
      async: true,
      data: $.toJSON(data),
      contentType:'application/json;charset=utf-8',
      dataType: 'json',
      success: function (data) {
        console.log("data",data)
      },
      error: function (error) {
        console.log("error",error);
      }
    })
  6. • nginx配置

  7.  location /test/ {
            proxy_pass https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=b38aa4d8-a08e-4a91;
            proxy_method POST;}
  8. • 这样就解决了跨域的问题,通过服务器转发来实现

  9. nginx转发请求从POST变成GET

    可以看到上面的配置是post请求到nginx,nginx在把请求转发到企业微信接口

    第一次http请求是post,第二次居然自动转换成get。

    原来nginx在配置location的时候,如果多了/,那么会自动变成get

    修改后如下

     location /test {
            proxy_pass https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=b38aa4d8-a08e-4a91;
            proxy_method POST;}

    相关文章

      网友评论

          本文标题:前端跨域问题的解决思路

          本文链接:https://www.haomeiwen.com/subject/qhhbvrtx.html