当我使用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;
render函数中的HTML代码:
<input
onChange = {this.handleUploadChange}
className={classes.uploadInput}
accept="image/*"
id="outlined-button-file"
multiple
type="file"
/>
答案 0 :(得分:0)
如果您使用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