vue开发:VUE axios发送跨域请求需要注意的问题

在实际项目中前端使用到vue,后端使用php进行开发。前端使用axios请求请求

关于跨域

跨域的概念这些就不说了,百度一大堆相关的资料信息。我就只在这里记录下我在使用当中遇到的问题,以纪念在逝去的几个小时中资料查找的艰辛。

不多说,直接上代码~~~~

同理,跨域的解决方案为cros。服务器 PHP端代码如下(laravel 中间件进行处理):

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
public function handle( $request , Closure $next )
   {
 
     if ( $request ->isMethod( 'OPTIONS' )) {
       $response = response( '' , 200);
     } else {
       $response = $next ( $request );
     }
     if (!method_exists( $response , 'header' )) {
       return $response ;
     }
     $response ->header( 'Access-Control-Allow-Methods' , 'HEAD, GET, POST, PUT, PATCH, DELETE, OPTIONS' );
     $response ->header(
       'Access-Control-Allow-Headers' ,
       'Content-Type, Content-Length, Authorization, Accept, X-Requested-With, Token'
     );
     $response ->header( 'Access-Control-Allow-Origin' , '*' );
     $response ->header( 'Access-Control-Max-Age' , 86400);
     return $response ;
   }

Vue端 axios 请求:

?
1
axios.post( 'http://XXXX.com' ,{name: 'test' });

这样写,在请求的时候就会遇到:


很坑爹有没有?明明是已经设置好了的啊,为毛是这样???

查找了很多资料才发现,axios在发送数据时需要字符串的方式进行发送,也就是说是放在form-data当中的。在实际项目中,为了方便,我引入了 qs 来帮助处理这块数据:

解决后的代码应该是:

?
1
2
3
4
import qs from 'qs' ;
axios.post( 'http://xxxxx.com' ,qs.stringify({name: 'test' })).then(re=>{
   console.log(re);
});

猜你喜欢

转载自blog.csdn.net/Generon/article/details/78292263