用fetch浏览器报CORS跨域请求解决


前端部分

function getHistory() {
  // var caData = new FormData();
  // caData.append('user_id', USER_ID);
  // console.log(99995,USER_ID)
  token = getCookie("token")
  // console.log(99996,USER_ID)
  // console.log(77775,JSON.stringify(caData),caData)
  // return false  application/json x-www-form-urlencoded
  let caData = {"user_id":USER_ID}
  fetch(`${DOMAIN}chathistory`, {
      method: 'POST',
      headers: {'Content-Type': 'application/json','token':token},
      body:JSON.stringify(caData)
    })
    .then(response => response.json())
    .then(chatHistory => {
      console.log(55551,chatHistory)
      if (chatHistory !='') {
        for (const row of chatHistory.data) {
            appendMessage(PERSON_NAME, PERSON_IMG, "right", row.human, "", row.create_time);
              res = row.ai.replace(/(?:\r\n|\r|\n)/g, '<br>');
            appendMessage(BOT_NAME, BOT_IMG, "left", res, "", row.create_time);
        }
      }
    })
    // .catch(errort => console.error(errort));
    .catch(err => {
      console.error(err);
    });
}

后端部分

用的thinkphp框架

在route里的空路由是,记得加上token,并且路由方法里加上HEAD (这个有版本号要求)

Route::miss(function() {
    if(app()->request->isOptions())
        return \think\Response::create('ok')->code(200)->header([
            'Access-Control-Allow-Origin'   => '*',
            'Access-Control-Allow-Headers'  => 'Authori-zation,Authorization, Content-Type, If-Match, If-Modified-Since, If-None-Match, If-Unmodified-Since, X-Requested-With, token',
            'Access-Control-Allow-Methods'  => 'GET,POST,PATCH,PUT,DELETE,OPTIONS,DELETE',
        ]);
    else
        return \think\Response::create()->code(403);
});

Route::rule('abc', '\app\admin\controller\abc@abc', 'POST|HEAD');


在中间件里的加上允许跨域的头,并且允许token

protected function initialize()
    {
        parent::initialize();
        // dump($_SERVER['HTTP_ORIGIN']);
        // 防止跨域
        if (isset($_SERVER['HTTP_ORIGIN'])) {
            header('Access-Control-Allow-Origin: '.$_SERVER['HTTP_ORIGIN']);
            header('Access-Control-Allow-Credentials: true');
            header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS');
            header("Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept, authKey, sessionId, token,projectid,debug");
            header("Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0");
        }
        
        $param =  $this->request->param(false);
        $this->param = $param;

    }