【问题标题】:Uploading image with axios (react) and PHP使用 axios (react) 和 PHP 上传图片
【发布时间】:2019-04-05 07:11:10
【问题描述】:

当我使用 Axios 向 PHP 文件发出请求时,我在控制台上收到此消息

Access to XMLHttpRequest at 'http://cp.com.br/cpnr-upload/' from 
origin 'http://localhost:3000' has been blocked by CORS policy: No 
'Access-Control-Allow-Origin' header is present on the requested resource.

问题是,目标文件已经在顶部: header('Access-Control-Allow-Origin: *');

React 中的请求代码:

handleUploadChange = (e) => {
let files = e.target.files;
let reader = new FileReader();
reader.readAsDataURL(files[0]);
reader.onload = (e) => {
  const url1 = "http://local.url/image-upload/";
  var data1 = new FormData();
  data1.set('action','upload');
  data1.set('file', e.target.result);
  return axios({
    method : "POST",
    url : url1,
    data : data1
  }).then(response => {
    console.warn("result", response);
  });
}
return;

渲染函数中的 HTML 代码:

<input
      onChange = {this.handleUploadChange}
      className={classes.uploadInput}
      accept="image/*"
      id="outlined-button-file"
      multiple
      type="file"
/>

【问题讨论】:

  • 如果您有 chrome,您可以再次发出请求并打开浏览器工具的网络选项卡并检查实际请求,看看您的请求发出的标头是什么。然后告诉我,我会帮你解决的。
  • 当您不使用 https 时,有时会显示此错误消息

标签: reactjs cors axios


【解决方案1】:

如果您使用 Laravel,请尝试使用此 https://github.com/barryvdh/laravel-cors。如果你是普通的 PHP,使用 Chrome 浏览器(我猜你是),使用这个扩展:https://chrome.google.com/webstore/detail/allow-control-allow-origi/nlfbmbojpeacfghkpbjhddihlkkiljbi。 当你使用 React 作为前端,PHP 作为后端时,这就是 CORS 问题。

PS:记住如果你是本地主机,使用 url 作为http://127.0.0.1 而不是http://localhost

【讨论】:

    猜你喜欢
    • 2021-01-29
    • 2021-03-10
    • 2020-08-17
    • 2018-03-26
    • 2019-10-06
    • 2020-10-22
    • 2019-03-26
    • 2021-01-13
    • 1970-01-01
    相关资源
    最近更新 更多