React通过fetch实现post上传json和formData

在react中利用fetch进行CORS跨域需要注意的点

当我们直接在fetch的url中输入完整的http时,就算加了"Access-Control-Allow-Origin": "*"也会报下面的错误:

Access to fetch at ‘http://xxx.xx.xxx.xx:8080/admin/onLogin’ from origin ‘http://localhost:3000’ has been blocked by CORS policy: Response to preflight request doesn’t pass access control check: No ‘Access-Control-Allow-Origin’ header is present on the requested resource. If an opaque response serves your needs, set the request’s mode to ‘no-cors’ to fetch the resource with CORS disabled.

POST http://xxx.xx.xxx.xx:8080/admin/onLogin net::ERR_FAILED

TypeError: Failed to fetch

在这里插入图片描述
为了解决这个错误,实现跨域,我们需要在package.json文件下加proxy,这样就不会报错并且实现跨域了。

  "proxy": "http://xxx.xx.xxx.xx:8080"

之后实现的上传json数据和上传formData就很简单了

上传json数据

fetch("/admin/onLogin", {
      method: "POST",
      headers: new Headers({
        "Access-Control-Allow-Origin": "*",
        "Content-Type": "application/json;charset=UTF-8",
      }),
      body: JSON.stringify({
        username: this.state.userName,
        password: this.state.password,
      }),
    })
      .then((res) => {
        return res.json().then((response) => {
          console.log(response);
        });
      })
      .catch((error) => {
        console.error(error);
      });

上传formData

var content = document.getElementById("content").innerHTML;
    var formData = new FormData();
    formData.append("type", this.state.value);
    formData.append("title", this.state.title);
    formData.append("content", content);
    for (var i = 0; i < this.state.fileList.length; i++) {
      formData.append("image", this.state.fileList[i].originFileObj);
    }
    fetch("/notice/send", {
      method: "POST",
      headers: new Headers({
        "Access-Control-Allow-Origin": "*",
        "User-Token": this.state.token,
      }),
      contentType: false,
      processData: false,
      body: formData,
      dataType: "text",
    })
      .then((res) => {
        return res.json().then((response) => {
          console.log(response);
        });
      })
      .catch((error) => {
        console.error(error);
      });
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值