axios 跨域访问thinkphp5 No 'Access-Control-Allow-Origin' header is present on the requested resource.

最简单的解决方法

html:

<!DOCTYPE html>
<html>
  <head>
    <title>json.html</title>
 
    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    <meta http-equiv="description" content="this is my page">
    <meta http-equiv="content-type" content="text/html; charset=UTF-8">
     <meta name="viewport" content="width=device-width, initial-scale=1">
     <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<!--     导入axios在线地址编辑器 -->
    <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
    <!--<link rel="stylesheet" type="text/css" href="./styles.css">-->

  </head>
  
  <body>
    <div id="main">    
 <input type="button" value="get请求" class="get">
  <input type="button" value="post请求" class="post">
 
         </div> 

  <script>  
 /*  get请求演示 */
 /*  https://autumnfish.cn/api/joke/list是返回笑话的API,
  请求参数是:num(笑话的个数)
  axios.get("https://autumnfish.cn/api/joke/list?num=3")
  */
  /* 天气的API */
        /* document.querySelector(".get").onclick=function(){
        
         axios.get("http://wthrcdn.etouch.cn/weather_mini?city=北京")
          .then(function(response){
           console.log(response);
           },function(err){
           console.log(err);
           })
      
      }    */
       
        document.querySelector(".get").onclick=function(){
        axios.get("需要访问的URL")
         .then(function(response){
           console.log(response);
           },function(err){
           console.log(err);
           })
      
      }  
              
  /*  post 请求演示 */ 
 /*  https://autumnfish.cn/api/user/reg这是用户注册的API,
  请求参数是:username(是用户名,是个字符串)
  返回注册成功或失败
  例如如果注册“jack”就回返回注册失败,用户存在;如果注册“丑八怪”返回注册成功。 */
  document.querySelector(".post").onclick=function(){
         axios.post("https://autumnfish.cn/api/user/reg",{username:"丑八怪"})
          .then(function(response){
           console.log(response);
           },function(err){
           console.log(err);
           })
      
      }            
 </script>
  </body>
  
</html>

thinkPHP 的处理方法:

入口文件增加三行:

header("Access-Control-Allow-Origin:*");
header("Access-Control-Allow-Methods:GET, POST, OPTIONS, DELETE");
header("Access-Control-Allow-Headers:DNT,X-Mx-ReqToken,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type, Accept-Language, Origin, Accept-Encoding");
//……

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值