账号密码登录
微信安全登录
微信扫描二维码登录

登录后绑定QQ、微信即可实现信息互通

手机验证码登录
找回密码返回
邮箱找回 手机找回
注册账号返回
其他登录方式
分享
  • 收藏
    X
    fetch请求设置Content-Type失败?
    • 2017-10-31 00:00
    • 11
    65
    0

    我看这篇文章https://segmentfault.com/a/11... 写的
    代码如下

    fetch(apiUrl, {
          method: "POST",
          body: JSON.stringify({ aaa: 1 }),
          headers: {
                'Content-Type': 'application/json',
          },
        });

    后端php

      header("Access-Control-Allow-Origin:*");
      header("Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept");
      var_dump($_REQUEST);

    结果

    array(0) {
    }

    chrome开发工具查看request header

    OPTIONS /LotteryAPP_MS/01Code/partner_react/api.php HTTP/1.1
    Host: 127.0.0.1
    Connection: keep-alive
    Pragma: no-cache
    Cache-Control: no-cache
    Access-Control-Request-Method: POST
    Origin: http://localhost:3000
    User-Agent: Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.115 Safari/537.36
    Access-Control-Request-Headers: content-type
    Accept: */*
    Referer: http://localhost:3000/
    Accept-Encoding: gzip, deflate, br
    Accept-Language: zh-CN,zh;q=0.8

    没有看到Content-Type: application/json,也没有看到参数,请求变成OPTIONS而不是POST了?
    我又试了一下,似乎和跨域有关?同域下的就不会这样?

    加上mode:'no-cors',这样就变成可以post请求,从chrome开发者工具上看,也能看到参数和返回

    fetch(apiUrl, {
          method: "POST",
          mode: 'no-cors',
          body: JSON.stringify({ aaa: 1 }),
          headers: {
                'Content-Type': 'application/json',
          },
        }).then(function(response) {
             response.text().then((r) => {
                console.log(r);
             }).catch((r) => {
                console.log(r);
             });
        }, function(error) {
             console.log(error);
        });

    但是,php还是获取不到,而且php的返回,这里用response.text()也拿不到

    1
    打赏
    收藏
    点击回答
    您的回答被采纳后将获得:提问者悬赏的 11 元积分
        全部回答
    • 0
    更多回答
    扫一扫访问手机版
    • 回到顶部
    • 回到顶部