axios跨域

 参考:http://www.ruanyifeng.com/blog/2016/04/cors.html

  • 遇到前后分离情况
    • 前端 a.com
    • 后端 server.a.com

       

  • 环境
    • vue全家桶前端 php后端lumen5.5

                  

  • 解决
    • 首先请求代码
    • return new Promise((resolve, reject) => {
          http.post(api.ADMIN_USER_LOGIN, userinfo).then(
              response => {
                  //200
                  if(response.data.status === configs.status.SUCCESS) {
                      commit(types.SET_USER, response.data.userinfo)
                      resolve(response)
                  }else {
                      reject(response)
                  }
                  
              },
              (err) => {reject(err.response)}
          )
      });

      请求后浏览器报错

      Failed to load http://server.a.com/xxxx: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://a.com' is therefore not allowed access. The response had HTTP status code 500.
    • 百度后发现此类请求已经归为非简单请求,了解原理后后端作出相应修改
       1 $router->options('/{origin:.*}', function(){
       2     $self_web = 'http://a.com';
       3 
       4     if(isset($_SERVER['HTTP_ORIGIN']) && $_SERVER['HTTP_ORIGIN'] === $self_web) {
       5         header('Access-Control-Allow-Origin: '.$self_web);
       6 
       7         $method = strtoupper($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_METHOD']);
       8         if(in_array($method, ['PUT', 'POST', 'GET'], true)) {
       9             header('Access-Control-Request-Method: '.$method);
      10         }
      11 
      12         $content_types = explode(',', $_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']);
      13         if($content_types) {
      14             $content_types = array_map(function($type){
      15                 return ucwords($type, '-');
      16             }, $content_types);
      17 
      18             if(count(array_diff($content_types, ['X-Requested-With', 'Content-Type'])) === 0) {
      19                 header("Access-Control-Allow-Headers: ".implode(',', $content_types));
      20             }
      21         }
      22     }
      23 });
  • end

                    

原文地址:https://www.cnblogs.com/maxilo/p/7896173.html