There is a cross-domain problem in the url, redirected to obtain Wechat token in koa (egg), which cannot be solved.

problem description

Failed to load https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxaf4b4a767b7ecdf9&redirect_uri=myurl&response_type=code&scope=snsapi_userinfo&state=STATE-sharpwechat_redirect: Redirect from "https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxaf4b4a767b7ecdfc&redirect_uri=myurl&response_type=code&scope=snsapi_userinfo&state=STATE-sharpwechat_redirect" to "https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxaf4b4a767b7ecdfc&redirect_uri=myurl&response_type=code&scope=snsapi_userinfo&state=STATE&connect_redirect=1-sharpwechat_redirect" has been blocked by CORS policy: No "Access-Control-Allow-Origin" header is present on the requested resource. Origin "null" is therefore not allowed access.

the environmental background of the problems and what methods you have tried

1 if the front and rear ends are not separated, the ctx.render ("index.nj",xxx)
2 can be obtained normally by using the method of rendering template. The subject adopts the front and rear separation mode, and nginx does the anti-proxy. The visited page is .html on cdn (where all cross-domain settings are normally released)
. In the background routing, if it is a general url, it can jump normally, for example

.
1() {
    ctx.redirect("/2")
   }
  

but in order to get Wechat"s openid, you must do the following jump
this.ctx.unsafeRedirect ("https://open.weixin.qq.com/connect/oauth2/authorize?appid="+AppID+"&redirect_uri="+return_uri+"&response_type=code&scope="+scope+"&state=STATE-sharpwechat_redirect"); A cross-domain error occurs when you get code
. Read https://harttle.land/2016/12/. (redirect CORS cross-domain request) to get the answer: if cross-domain failure occurs in any of the multiple redirects, the whole process completely fails.

try a solution

1 jsmyurl.cnmyurl.cn/index.html
2 redirect()
    // 
    this.ctx.set("Access-Control-Allow-Origin", "*");
    //  http://localhost:8080 
    // ctx.set("Access-Control-Allow-Origin", "http://localhost:8080"); 
    // HTTP
    this.ctx.set("Access-Control-Allow-Methods", "OPTIONS, GET, PUT, POST, DELETE");
    // .
    this.ctx.set("Access-Control-Allow-Headers", "x-requested-with, accept, origin, content-type");
    // OriginAccess-Control-Request-MethodAccess-Control-Request-Headers
    // Content-Type
    this.ctx.set("Content-Type", "application/json;charset=utf-8");
    // CookieCookieCORS
    // cookie"Access-Control-Allow-Origin""*";
    this.ctx.set("Access-Control-Allow-Credentials", true);

related codes

this.ctx.unsafeRedirect("https://open.weixin.qq.com/connect/oauth2/authorize?appid="+AppID+"&redirect_uri="+return_uri+"&response_type=code&scope="+scope+"&state=STATE-sharpwechat_redirect");

what result do you expect? What is the error message actually seen?

ask if you have been exposed to type cross-domain problems. Ask Daniel to help!

Menu