关于VUE使用axios异步请求时的跨域处理方法

vue的异步请求在2.0以后推荐使用axios,但是axios默认是不支持跨域的,需要做一定的处理,以下讲解处理axios跨域的解决办法

前端示例代码如下:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<title>vue异步请求示例</title>
</head>

<body>
<div id="app">
  {{ message }}
</div>
<script language="javascript">
var app = new Vue({
  el: '#app',
  data: {
    message: '我去做异步请求啦!'
  },
  mounted () {
	axios({
		url:'/crm/publics/login',
		headers:{
			'X-Requested-With':'XMLHttpRequest'
			},
		method: 'post',
		responseType: 'json', // 默认的
		data:{'account':'admin','password':'admin1231'},
	}).then(function(response){
		console.log(response);
		console.log(response.data);
	}).catch(function(error){
		console.log(error);
	})
  }
})
</script>
</body>
</html>

PHP端我使用的是thinkphp5.1的框架,框架需要做如下的处理;

index.php增加跨域的功能,注意增加的3个header方法;

header('Access-Control-Allow-Origin:*');//允许所有来源访问,但是建议指定跨域的源

重点说一下下面的语句:

header("Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept, Authorization");

如果没有这句,前端axios的异步需要做一定的修改。因为当跨域时,无论你是post还是get方式,axios都会把他修改为options方式,而我们在PHP端的header('Access-Control-Allow-Method:POST,GET,PUT,DELETE,OPTIONS');指定了可以通过OPTIONS。

// [ 应用入口文件 ]
namespace think;
header('Access-Control-Allow-Origin:*');//允许所有来源访问
header('Access-Control-Allow-Method:POST,GET,PUT,DELETE,OPTIONS');//允许访问的方式
header("Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept, Authorization");
// 加载基础文件
require __DIR__ . '/../thinkphp/base.php';

// 支持事先使用静态方法设置Request对象和Config对象

// 执行应用并响应
Container::get('app')->run()->send();

第三步要注意的是,返回json给前端,因为在前端时是声明了返回json数据,所以在thinkphp5.1的controller中需要使用以下的方式返回

namespace app\crm\controller;
use app\common\controller\Web;
//use app\common\controller\Web;
class Publics extends Web{
    /**
     * |用户登录
     * @return \think\response\View
     */
    public function login(){
        //post方式提交
        if (request()->isPost()) {
            $where['account']=input('account');
            $user=model('user')->field('id,roles,account,nickname,password,status')->where($where)->find();
            if (!$user) {
                $this->result('','400','该用户不存在');
            }
            $user = $user->toArray();
            if ($user['password'] != md5(input('password'))) {
                $this->result('','400','用户名或者密码错误');
            }
            if ($user['status'] != 1) {
                $this->result('','400','该用户已被禁用或者不存在');
            }

            $this->result($key,'200','ok','json'); //要显式的告诉前端返回json
        }
    }
发布了108 篇原创文章 · 获赞 10 · 访问量 20万+

猜你喜欢

转载自blog.csdn.net/emtit2008/article/details/96137646
今日推荐