Using Koa2 to do OAuth, the browser reported 404 without waiting for the server to get the data from the OAuth server.

for example:
I use Github"s OAuth,
when the browser requests,
I wanted to send an asynchronous request for authentication to github,
but the browser didn"t wait for me to get the information from github and response it to the browser.
browser reported 404,
after a few seconds, koa also fetch to the normal data of OAuth server, but actually disconnected from browser.
this is why.

the code is as follows:

let result = await fetch(path, { 
    method: "POST",
    headers: {
        "Content-Type": "application/json"
    },
    body: JSON.stringify(params)
  })
  let body = await result.text()
  //accesstoken
  let resultArray = body.split("&")
  let resultObj = {}
  resultArray.forEach(element => {
    let key = element.split("=")[0]
    let value = element.split("=")[1]
    resultObj[key] = value
  });
  //accesstoken
  if (!resultObj.access_token) {
    ctx.response.body = {
      code: "404",
      data: resultObj
    }
    return
  }
  let access_token = resultObj.access_token
  let userInfo = await fetch("https://api.github.com/user?access_token=" + access_token)
  let userData = await userInfo.json()
  console.log("success to get userData", userData) // 404
  ctx.response.body = {
    code: "200",
    data: userData
  } // 

Apr.12,2022
Menu